coverage-report

Code coverage report for All files

npmtest-npm (v0.0.1)

Code coverage report for All files

Statements: 19.05% (7513 / 39430)      Branches: 3.77% (863 / 22874)      Functions: 5.94% (296 / 4986)      Lines: 20.54% (7450 / 36275)      Ignored: 99 statements, 1 function, 96 branches     

File Statements Branches Functions Lines
node-npmtest-npm/ 100% (153 / 153) 100% (126 / 126) 100% (28 / 28) 100% (153 / 153)
node-npmtest-npm/node_modules/npm/lib/ 16.64% (787 / 4729) 0.51% (13 / 2559) 2.07% (15 / 724) 18.46% (785 / 4252)
node-npmtest-npm/node_modules/npm/lib/cache/ 20.34% (178 / 875) 0% (0 / 455) 0% (0 / 132) 22.19% (178 / 802)
node-npmtest-npm/node_modules/npm/lib/config/ 28% (154 / 550) 12.33% (36 / 292) 7.69% (6 / 78) 29.8% (152 / 510)
node-npmtest-npm/node_modules/npm/lib/doctor/ 26.39% (38 / 144) 0% (0 / 45) 0% (0 / 25) 28.79% (38 / 132)
node-npmtest-npm/node_modules/npm/lib/install/ 11.37% (72 / 633) 0% (0 / 380) 0% (0 / 121) 13.24% (72 / 544)
node-npmtest-npm/node_modules/npm/lib/search/ 22.47% (71 / 316) 0% (0 / 152) 0% (0 / 73) 23.67% (71 / 300)
node-npmtest-npm/node_modules/npm/lib/utils/ 23.85% (307 / 1287) 3.42% (24 / 702) 4.57% (8 / 175) 25.87% (304 / 1175)
node-npmtest-npm/node_modules/npm/lib/utils/completion/ 17.95% (21 / 117) 0% (0 / 64) 0% (0 / 27) 19.63% (21 / 107)
node-npmtest-npm/node_modules/npm/node_modules/JSONStream/ 4.14% (7 / 169) 1.69% (2 / 118) 0% (0 / 16) 4.43% (7 / 158)
node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/jsonparse/ 17.78% (61 / 343) 0% (0 / 245) 0% (0 / 14) 21.48% (61 / 284)
node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/through/ 8.45% (6 / 71) 0% (0 / 34) 0% (0 / 13) 9.52% (6 / 63)
node-npmtest-npm/node_modules/npm/node_modules/abbrev/ 85.71% (30 / 35) 91.67% (22 / 24) 40% (2 / 5) 85.29% (29 / 34)
node-npmtest-npm/node_modules/npm/node_modules/ansi-regex/ 100% (2 / 2) 100% (0 / 0) 100% (1 / 1) 100% (2 / 2)
node-npmtest-npm/node_modules/npm/node_modules/ansicolors/ 85.71% (12 / 14) 100% (0 / 0) 50% (2 / 4) 85.71% (12 / 14)
node-npmtest-npm/node_modules/npm/node_modules/ansistyles/ 66.67% (4 / 6) 100% (0 / 0) 50% (1 / 2) 66.67% (4 / 6)
node-npmtest-npm/node_modules/npm/node_modules/aproba/ 53.75% (43 / 80) 56.41% (22 / 39) 40% (10 / 25) 60.87% (42 / 69)
node-npmtest-npm/node_modules/npm/node_modules/archy/ 5.56% (1 / 18) 0% (0 / 22) 0% (0 / 3) 6.67% (1 / 15)
node-npmtest-npm/node_modules/npm/node_modules/asap/ 26.15% (17 / 65) 0% (0 / 22) 0% (0 / 6) 26.15% (17 / 65)
node-npmtest-npm/node_modules/npm/node_modules/call-limit/ 12.07% (7 / 58) 0% (0 / 20) 0% (0 / 12) 12.5% (7 / 56)
node-npmtest-npm/node_modules/npm/node_modules/chownr/ 15% (6 / 40) 0% (0 / 26) 0% (0 / 7) 18.18% (6 / 33)
node-npmtest-npm/node_modules/npm/node_modules/cmd-shim/ 18.67% (14 / 75) 0% (0 / 28) 0% (0 / 16) 19.44% (14 / 72)
node-npmtest-npm/node_modules/npm/node_modules/columnify/ 13.16% (35 / 266) 0% (0 / 126) 0% (0 / 49) 14.29% (35 / 245)
node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/ 21.43% (9 / 42) 0% (0 / 46) 0% (0 / 6) 26.47% (9 / 34)
node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/ 28.57% (2 / 7) 0% (0 / 4) 0% (0 / 2) 28.57% (2 / 7)
node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/node_modules/clone/ 19.54% (17 / 87) 5.56% (3 / 54) 10% (1 / 10) 20.48% (17 / 83)
node-npmtest-npm/node_modules/npm/node_modules/config-chain/ 14.04% (25 / 178) 0% (0 / 95) 4% (1 / 25) 14.97% (25 / 167)
node-npmtest-npm/node_modules/npm/node_modules/config-chain/node_modules/proto-list/ 7.84% (4 / 51) 0% (0 / 22) 0% (0 / 18) 8.89% (4 / 45)
node-npmtest-npm/node_modules/npm/node_modules/debuglog/ 35.71% (5 / 14) 44.44% (4 / 9) 0% (0 / 3) 35.71% (5 / 14)
node-npmtest-npm/node_modules/npm/node_modules/dezalgo/ 28.57% (4 / 14) 0% (0 / 2) 0% (0 / 4) 28.57% (4 / 14)
node-npmtest-npm/node_modules/npm/node_modules/editor/ 13.33% (2 / 15) 0% (0 / 12) 0% (0 / 2) 15.38% (2 / 13)
node-npmtest-npm/node_modules/npm/node_modules/fs-vacuum/ 15.19% (12 / 79) 0% (0 / 59) 0% (0 / 9) 16.44% (12 / 73)
node-npmtest-npm/node_modules/npm/node_modules/fs-write-stream-atomic/ 26.26% (26 / 99) 2.86% (1 / 35) 0% (0 / 23) 27.96% (26 / 93)
node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/ 7.77% (15 / 193) 0% (0 / 181) 0% (0 / 19) 9.04% (15 / 166)
node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/ 13.16% (15 / 114) 0% (0 / 86) 0% (0 / 20) 14.56% (15 / 103)
node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/ 10.77% (46 / 427) 0% (0 / 260) 5.88% (2 / 34) 11.41% (46 / 403)
node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/ 17.27% (19 / 110) 0% (0 / 55) 0% (0 / 13) 17.59% (19 / 108)
node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/ 14.29% (5 / 35) 0% (0 / 26) 0% (0 / 3) 15.15% (5 / 33)
node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/ 20% (2 / 10) 25% (1 / 4) 0% (0 / 2) 22.22% (2 / 9)
node-npmtest-npm/node_modules/npm/node_modules/fstream/ 100% (16 / 16) 100% (0 / 0) 100% (0 / 0) 100% (16 / 16)
node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/ 16.37% (173 / 1057) 0.16% (1 / 610) 0% (0 / 140) 17.71% (173 / 977)
node-npmtest-npm/node_modules/npm/node_modules/glob/ 13.15% (114 / 867) 0% (0 / 579) 0% (0 / 72) 13.18% (114 / 865)
node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/ 19.19% (38 / 198) 2.65% (3 / 113) 0% (0 / 21) 20.43% (38 / 186)
node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/ 10.77% (46 / 427) 0% (0 / 260) 5.88% (2 / 34) 11.41% (46 / 403)
node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/ 17.27% (19 / 110) 0% (0 / 55) 0% (0 / 13) 17.59% (19 / 108)
node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/ 14.29% (5 / 35) 0% (0 / 26) 0% (0 / 3) 15.15% (5 / 33)
node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/ 20% (2 / 10) 25% (1 / 4) 0% (0 / 2) 22.22% (2 / 9)
node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/path-is-absolute/ 45.45% (5 / 11) 12.5% (1 / 8) 0% (0 / 2) 45.45% (5 / 11)
node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/ 36.5% (165 / 452) 14.71% (35 / 238) 22.73% (20 / 88) 37.95% (159 / 419)
node-npmtest-npm/node_modules/npm/node_modules/has-unicode/ 85.71% (6 / 7) 40% (2 / 5) 100% (1 / 1) 100% (6 / 6)
node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/ 26.21% (38 / 145) 3.8% (3 / 79) 10% (3 / 30) 28.46% (37 / 130)
node-npmtest-npm/node_modules/npm/node_modules/iferr/ 46.15% (12 / 26) 0% (0 / 10) 28.57% (2 / 7) 46.15% (12 / 26)
node-npmtest-npm/node_modules/npm/node_modules/imurmurhash/ 23.19% (16 / 69) 17.14% (6 / 35) 60% (3 / 5) 23.19% (16 / 69)
node-npmtest-npm/node_modules/npm/node_modules/inflight/ 24.14% (7 / 29) 0% (0 / 4) 0% (0 / 5) 25% (7 / 28)
node-npmtest-npm/node_modules/npm/node_modules/inherits/ 66.67% (4 / 6) 50% (1 / 2) 100% (0 / 0) 80% (4 / 5)
node-npmtest-npm/node_modules/npm/node_modules/ini/ 11% (11 / 100) 1.06% (1 / 94) 0% (0 / 14) 11.7% (11 / 94)
node-npmtest-npm/node_modules/npm/node_modules/init-package-json/ 15.38% (14 / 91) 0% (0 / 57) 0% (0 / 16) 16.47% (14 / 85)
node-npmtest-npm/node_modules/npm/node_modules/init-package-json/node_modules/promzard/ 14.12% (24 / 170) 0% (0 / 82) 0% (0 / 23) 14.72% (24 / 163)
node-npmtest-npm/node_modules/npm/node_modules/lazy-property/ 25% (2 / 8) 100% (0 / 0) 0% (0 / 3) 25% (2 / 8)
node-npmtest-npm/node_modules/npm/node_modules/lockfile/ 13.33% (26 / 195) 4% (4 / 100) 0% (0 / 32) 14.77% (26 / 176)
node-npmtest-npm/node_modules/npm/node_modules/lodash.clonedeep/ 38.35% (153 / 399) 16.56% (51 / 308) 11.76% (10 / 85) 38.35% (153 / 399)
node-npmtest-npm/node_modules/npm/node_modules/lodash.union/ 40.86% (114 / 279) 15.22% (28 / 184) 19.3% (11 / 57) 40.86% (114 / 279)
node-npmtest-npm/node_modules/npm/node_modules/lodash.without/ 41.27% (104 / 252) 15.58% (24 / 154) 17.31% (9 / 52) 41.27% (104 / 252)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/ 100% (9 / 9) 100% (0 / 0) 100% (0 / 0) 100% (9 / 9)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/concat-stream/ 15.6% (17 / 109) 3.13% (2 / 64) 0% (0 / 12) 18.09% (17 / 94)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/ 13.33% (24 / 180) 0% (0 / 113) 0% (0 / 26) 16.44% (24 / 146)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/ 8.47% (5 / 59) 0% (0 / 44) 0% (0 / 9) 10.2% (5 / 49)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/node_modules/once/ 53.85% (7 / 13) 0% (0 / 2) 25% (1 / 4) 58.33% (7 / 12)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/stream-shift/ 25% (3 / 12) 0% (0 / 8) 0% (0 / 2) 27.27% (3 / 11)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/ 9.09% (6 / 66) 0% (0 / 51) 0% (0 / 11) 10.91% (6 / 55)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/node_modules/once/ 53.85% (7 / 13) 0% (0 / 2) 25% (1 / 4) 58.33% (7 / 12)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/flush-write-stream/ 21.74% (10 / 46) 0% (0 / 28) 0% (0 / 5) 28.57% (10 / 35)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/from2/ 30.67% (23 / 75) 11.9% (5 / 42) 16.67% (2 / 12) 34.33% (23 / 67)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pump/ 19.35% (12 / 62) 0% (0 / 40) 0% (0 / 13) 24% (12 / 50)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pumpify/ 25.58% (11 / 43) 0% (0 / 18) 14.29% (1 / 7) 29.73% (11 / 37)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/ 18.6% (8 / 43) 0% (0 / 20) 0% (0 / 5) 22.22% (8 / 36)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/node_modules/stream-shift/ 25% (3 / 12) 0% (0 / 8) 0% (0 / 2) 27.27% (3 / 11)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/ 22% (11 / 50) 0% (0 / 18) 10% (1 / 10) 22.45% (11 / 49)
node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/node_modules/xtend/ 30% (3 / 10) 0% (0 / 2) 0% (0 / 1) 30% (3 / 10)
node-npmtest-npm/node_modules/npm/node_modules/mkdirp/ 10.34% (6 / 58) 0% (0 / 42) 0% (0 / 6) 11.32% (6 / 53)
node-npmtest-npm/node_modules/npm/node_modules/nopt/lib/ 6.37% (17 / 267) 1.35% (3 / 223) 0% (0 / 23) 7.02% (17 / 242)
node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/ 41.46% (17 / 41) 0% (0 / 36) 8.33% (1 / 12) 44.74% (17 / 38)
node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/ 23.08% (3 / 13) 3.57% (1 / 28) 0% (0 / 1) 23.08% (3 / 13)
node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/ 30% (3 / 10) 6.67% (1 / 15) 0% (0 / 1) 30% (3 / 10)
node-npmtest-npm/node_modules/npm/node_modules/normalize-git-url/ 11.11% (2 / 18) 0% (0 / 13) 0% (0 / 1) 11.11% (2 / 18)
node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/ 11.31% (37 / 327) 0% (0 / 268) 3.92% (2 / 51) 12.54% (37 / 295)
node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/ 40% (2 / 5) 0% (0 / 2) 0% (0 / 1) 40% (2 / 5)
node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/node_modules/builtin-modules/ 100% (3 / 3) 100% (2 / 2) 100% (1 / 1) 100% (3 / 3)
node-npmtest-npm/node_modules/npm/node_modules/npm-cache-filename/ 26.67% (4 / 15) 0% (0 / 6) 0% (0 / 2) 26.67% (4 / 15)
node-npmtest-npm/node_modules/npm/node_modules/npm-package-arg/ 20.37% (22 / 108) 4.88% (4 / 82) 0% (0 / 8) 20.75% (22 / 106)
node-npmtest-npm/node_modules/npm/node_modules/npm-registry-client/ 10.91% (6 / 55) 0% (0 / 30) 0% (0 / 2) 12.24% (6 / 49)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/ 28.51% (63 / 221) 3.77% (4 / 106) 9.38% (3 / 32) 33.33% (62 / 186)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/ 41.54% (54 / 130) 0% (0 / 32) 13.04% (3 / 23) 43.2% (54 / 125)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/ 46.51% (20 / 43) 50% (2 / 4) 20% (2 / 10) 45.24% (19 / 42)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/console-control-strings/ 57.5% (23 / 40) 20% (4 / 20) 12.5% (2 / 16) 57.89% (22 / 38)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/ 34.72% (201 / 579) 19.02% (62 / 326) 21.79% (17 / 78) 38.64% (199 / 515)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/ 48.84% (21 / 43) 25% (5 / 20) 60% (3 / 5) 48.84% (21 / 43)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/ 67.42% (60 / 89) 38.24% (13 / 34) 41.67% (5 / 12) 67.42% (60 / 89)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/ 22.22% (4 / 18) 0% (0 / 13) 0% (0 / 1) 22.22% (4 / 18)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/ 6.25% (1 / 16) 0% (0 / 21) 0% (0 / 1) 6.25% (1 / 16)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/ 28.57% (2 / 7) 0% (0 / 35) 0% (0 / 1) 28.57% (2 / 7)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/ 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/ 18.18% (8 / 44) 0% (0 / 20) 0% (0 / 4) 19.51% (8 / 41)
node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/set-blocking/ 100% (4 / 4) 80% (4 / 5) 100% (2 / 2) 100% (4 / 4)
node-npmtest-npm/node_modules/npm/node_modules/once/ 34.62% (9 / 26) 0% (0 / 6) 14.29% (1 / 7) 36% (9 / 25)
node-npmtest-npm/node_modules/npm/node_modules/opener/ 18.18% (4 / 22) 13.04% (3 / 23) 0% (0 / 3) 18.18% (4 / 22)
node-npmtest-npm/node_modules/npm/node_modules/osenv/ 63.41% (26 / 41) 27.78% (10 / 36) 50% (6 / 12) 68.42% (26 / 38)
node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-homedir/ 23.08% (3 / 13) 3.57% (1 / 28) 0% (0 / 1) 23.08% (3 / 13)
node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-tmpdir/ 80% (8 / 10) 46.67% (7 / 15) 100% (1 / 1) 80% (8 / 10)
node-npmtest-npm/node_modules/npm/node_modules/path-is-inside/lib/ 25% (3 / 12) 0% (0 / 7) 0% (0 / 2) 25% (3 / 12)
node-npmtest-npm/node_modules/npm/node_modules/read-cmd-shim/ 21.05% (8 / 38) 0% (0 / 14) 0% (0 / 8) 22.86% (8 / 35)
node-npmtest-npm/node_modules/npm/node_modules/read-installed/ 11.52% (22 / 191) 0% (0 / 143) 0% (0 / 28) 12.79% (22 / 172)
node-npmtest-npm/node_modules/npm/node_modules/read-installed/node_modules/util-extend/ 22.22% (2 / 9) 0% (0 / 4) 0% (0 / 1) 25% (2 / 8)
node-npmtest-npm/node_modules/npm/node_modules/read-package-json/ 15.3% (43 / 281) 0% (0 / 140) 0% (0 / 54) 17.92% (43 / 240)
node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/ 42.86% (3 / 7) 100% (0 / 0) 0% (0 / 1) 42.86% (3 / 7)
node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/node_modules/jju/ 50% (6 / 12) 100% (0 / 0) 0% (0 / 6) 50% (6 / 12)
node-npmtest-npm/node_modules/npm/node_modules/read-package-tree/ 25.31% (41 / 162) 0% (0 / 63) 0% (0 / 27) 27.15% (41 / 151)
node-npmtest-npm/node_modules/npm/node_modules/read/lib/ 9.21% (7 / 76) 0% (0 / 47) 0% (0 / 6) 9.46% (7 / 74)
node-npmtest-npm/node_modules/npm/node_modules/read/node_modules/mute-stream/ 34.29% (24 / 70) 0% (0 / 47) 6.67% (1 / 15) 36.51% (23 / 63)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/ 92.31% (12 / 13) 57.14% (4 / 7) 100% (1 / 1) 92.31% (12 / 13)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/ 16.38% (161 / 983) 2.59% (15 / 580) 2.75% (3 / 109) 18.39% (160 / 870)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/internal/streams/ 18.87% (10 / 53) 0% (0 / 14) 0% (0 / 7) 22.73% (10 / 44)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/buffer-shims/ 10.81% (8 / 74) 1.59% (1 / 63) 0% (0 / 4) 10.81% (8 / 74)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/core-util-is/lib/ 63.83% (30 / 47) 0% (0 / 12) 0% (0 / 15) 63.83% (30 / 47)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/isarray/ 66.67% (2 / 3) 50% (1 / 2) 0% (0 / 1) 66.67% (2 / 3)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/process-nextick-args/ 13.64% (3 / 22) 28.57% (4 / 14) 0% (0 / 5) 13.64% (3 / 22)
node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/util-deprecate/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-npm/node_modules/npm/node_modules/readdir-scoped-modules/ 21.95% (9 / 41) 0% (0 / 15) 0% (0 / 11) 21.95% (9 / 41)
node-npmtest-npm/node_modules/npm/node_modules/realize-package-specifier/ 18.18% (6 / 33) 0% (0 / 29) 0% (0 / 4) 22.22% (6 / 27)
node-npmtest-npm/node_modules/npm/node_modules/request/ 7.39% (66 / 893) 0.15% (1 / 661) 1.2% (1 / 83) 7.47% (66 / 884)
node-npmtest-npm/node_modules/npm/node_modules/request/lib/ 16.84% (97 / 576) 0.25% (1 / 401) 2.7% (2 / 74) 16.96% (97 / 572)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws-sign2/ 42.22% (19 / 45) 0% (0 / 14) 0% (0 / 9) 45.24% (19 / 42)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/ 18.18% (42 / 231) 0% (0 / 197) 7.32% (3 / 41) 19.63% (42 / 214)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/caseless/ 14.55% (8 / 55) 0% (0 / 24) 0% (0 / 13) 17.02% (8 / 47)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/lib/ 19.64% (22 / 112) 0% (0 / 43) 0% (0 / 20) 20% (22 / 110)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/ 22.95% (14 / 61) 0% (0 / 14) 0% (0 / 13) 22.95% (14 / 61)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/extend/ 12.5% (5 / 40) 0% (0 / 47) 0% (0 / 3) 12.5% (5 / 40)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/forever-agent/ 19.75% (16 / 81) 0% (0 / 53) 0% (0 / 8) 20% (16 / 80)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/ 16.67% (32 / 192) 0% (0 / 121) 0% (0 / 25) 16.67% (32 / 192)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/ 35.9% (14 / 39) 0% (0 / 16) 0% (0 / 7) 35.9% (14 / 39)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/ 29.82% (17 / 57) 0% (0 / 34) 0% (0 / 13) 30.36% (17 / 56)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/ 65.96% (62 / 94) 36.36% (8 / 22) 8.7% (2 / 23) 63.1% (53 / 84)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/ 17.26% (78 / 452) 2.48% (6 / 242) 0% (0 / 52) 18.43% (75 / 407)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/ 19.22% (123 / 640) 0.24% (1 / 424) 1.41% (1 / 71) 21.71% (122 / 562)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/ 4.05% (80 / 1974) 4.39% (58 / 1321) 0% (0 / 23) 4.08% (80 / 1963)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/co/ 19.1% (17 / 89) 0% (0 / 42) 0% (0 / 20) 22.97% (17 / 74)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/json-stable-stringify/ 6.56% (4 / 61) 5.88% (3 / 51) 0% (0 / 9) 7.55% (4 / 53)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/har-schema/lib/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/ 16.67% (59 / 354) 0% (0 / 332) 0% (0 / 32) 16.67% (59 / 354)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/boom/lib/ 26.92% (35 / 130) 0% (0 / 52) 0% (0 / 32) 26.92% (35 / 130)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/ 22.22% (6 / 27) 0% (0 / 14) 0% (0 / 3) 22.22% (6 / 27)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/ 13.33% (66 / 495) 3.72% (13 / 349) 1.69% (1 / 59) 13.33% (66 / 495)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/lib/ 9.09% (16 / 176) 0% (0 / 83) 0% (0 / 22) 9.64% (16 / 166)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/ 18.64% (71 / 381) 0% (0 / 188) 0% (0 / 30) 18.68% (71 / 380)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/assert-plus/ 49.45% (45 / 91) 17.02% (8 / 47) 26.92% (7 / 26) 49.45% (45 / 91)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/lib/ 26.36% (58 / 220) 0% (0 / 76) 0% (0 / 28) 26.36% (58 / 220)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/extsprintf/lib/ 8.11% (6 / 74) 0% (0 / 46) 0% (0 / 3) 8.11% (6 / 74)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/json-schema/lib/ 12.41% (18 / 145) 2.55% (5 / 196) 15.38% (2 / 13) 12.68% (18 / 142)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/lib/ 24.66% (18 / 73) 0% (0 / 54) 0% (0 / 7) 24.66% (18 / 73)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/ 19.15% (307 / 1603) 0% (0 / 667) 0.7% (1 / 142) 19.21% (307 / 1598)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/ 12.89% (204 / 1583) 0% (0 / 543) 5.38% (5 / 93) 12.83% (203 / 1582)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/ 16.57% (57 / 344) 1.31% (2 / 153) 0% (0 / 38) 16.57% (57 / 344)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/ 48.91% (45 / 92) 16.33% (8 / 49) 25.93% (7 / 27) 48.91% (45 / 92)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/is-typedarray/ 72.73% (8 / 11) 0% (0 / 11) 0% (0 / 3) 72.73% (8 / 11)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/isstream/ 69.23% (9 / 13) 0% (0 / 8) 0% (0 / 4) 69.23% (9 / 13)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/json-stringify-safe/ 20% (4 / 20) 0% (0 / 14) 0% (0 / 4) 23.53% (4 / 17)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/ 50% (32 / 64) 21.43% (12 / 56) 33.33% (2 / 6) 50.79% (32 / 63)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/node_modules/mime-db/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/oauth-sign/ 29.31% (17 / 58) 0% (0 / 28) 0% (0 / 13) 29.31% (17 / 58)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/performance-now/lib/ 52.38% (11 / 21) 50% (6 / 12) 33.33% (2 / 6) 52.38% (11 / 21)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/ 12.41% (34 / 274) 0.75% (2 / 265) 4.35% (1 / 23) 12.41% (34 / 274)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/safe-buffer/ 31.25% (10 / 32) 27.78% (5 / 18) 14.29% (1 / 7) 31.25% (10 / 32)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/stringstream/ 22.08% (17 / 77) 0% (0 / 35) 0% (0 / 10) 25% (17 / 68)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/ 19.26% (146 / 758) 1.55% (8 / 515) 6.9% (6 / 87) 19.36% (146 / 754)
node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tunnel-agent/ 19.42% (27 / 139) 5.88% (2 / 34) 0% (0 / 23) 19.57% (27 / 138)
node-npmtest-npm/node_modules/npm/node_modules/retry/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-npm/node_modules/npm/node_modules/retry/lib/ 12.12% (16 / 132) 0% (0 / 61) 0% (0 / 20) 12.12% (16 / 132)
node-npmtest-npm/node_modules/npm/node_modules/rimraf/ 9.91% (21 / 212) 0% (0 / 152) 0% (0 / 27) 9.95% (21 / 211)
node-npmtest-npm/node_modules/npm/node_modules/semver/ 52.09% (349 / 670) 25.96% (95 / 366) 47.56% (39 / 82) 52.58% (347 / 660)
node-npmtest-npm/node_modules/npm/node_modules/sha/ 17.11% (13 / 76) 2.78% (1 / 36) 0% (0 / 11) 18.84% (13 / 69)
node-npmtest-npm/node_modules/npm/node_modules/slide/lib/ 19.7% (13 / 66) 0% (0 / 40) 0% (0 / 13) 23.08% (12 / 52)
node-npmtest-npm/node_modules/npm/node_modules/sorted-object/lib/ 20% (1 / 5) 100% (0 / 0) 0% (0 / 2) 20% (1 / 5)
node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/ 12.2% (5 / 41) 0% (0 / 24) 0% (0 / 6) 14.29% (5 / 35)
node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/ 31.88% (22 / 69) 8.33% (3 / 36) 18.18% (2 / 11) 36.67% (22 / 60)
node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/ 88.89% (8 / 9) 75% (3 / 4) 100% (0 / 0) 88.89% (8 / 9)
node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/ 14.8% (123 / 831) 1.41% (7 / 497) 1.96% (2 / 102) 14.89% (123 / 826)
node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/core-util-is/lib/ 63.83% (30 / 47) 0% (0 / 12) 0% (0 / 15) 63.83% (30 / 47)
node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/ 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/stream-iterate/ 5.36% (3 / 56) 0% (0 / 24) 0% (0 / 9) 6.52% (3 / 46)
node-npmtest-npm/node_modules/npm/node_modules/strip-ansi/ 66.67% (2 / 3) 0% (0 / 2) 0% (0 / 1) 66.67% (2 / 3)
node-npmtest-npm/node_modules/npm/node_modules/tar/ 100% (48 / 48) 100% (6 / 6) 100% (3 / 3) 100% (47 / 47)
node-npmtest-npm/node_modules/npm/node_modules/tar/lib/ 11.9% (102 / 857) 0.21% (1 / 467) 1.01% (1 / 99) 12.66% (101 / 798)
node-npmtest-npm/node_modules/npm/node_modules/tar/node_modules/block-stream/ 9.52% (10 / 105) 1.39% (1 / 72) 0% (0 / 8) 10.2% (10 / 98)
node-npmtest-npm/node_modules/npm/node_modules/text-table/ 8.47% (5 / 59) 0% (0 / 38) 0% (0 / 14) 9.43% (5 / 53)
node-npmtest-npm/node_modules/npm/node_modules/uid-number/ 7.69% (3 / 39) 6.25% (2 / 32) 0% (0 / 2) 10.34% (3 / 29)
node-npmtest-npm/node_modules/npm/node_modules/umask/ 36.84% (14 / 38) 0% (0 / 26) 20% (1 / 5) 36.84% (14 / 38)
node-npmtest-npm/node_modules/npm/node_modules/unique-filename/ 75% (3 / 4) 0% (0 / 2) 0% (0 / 1) 75% (3 / 4)
node-npmtest-npm/node_modules/npm/node_modules/unique-filename/node_modules/unique-slug/ 42.86% (3 / 7) 0% (0 / 2) 0% (0 / 1) 42.86% (3 / 7)
node-npmtest-npm/node_modules/npm/node_modules/unpipe/ 13.64% (3 / 22) 0% (0 / 12) 0% (0 / 2) 13.64% (3 / 22)
node-npmtest-npm/node_modules/npm/node_modules/uuid/ 28.57% (18 / 63) 0% (0 / 45) 0% (0 / 2) 28.57% (18 / 63)
node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/ 75% (9 / 12) 0% (0 / 2) 50% (1 / 2) 75% (9 / 12)
node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/ 25% (7 / 28) 0% (0 / 16) 0% (0 / 3) 25% (7 / 28)
node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-correct/ 17.57% (13 / 74) 0% (0 / 22) 0% (0 / 27) 17.57% (13 / 74)
node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/ 2.51% (24 / 958) 1.18% (6 / 509) 12.12% (4 / 33) 75% (3 / 4)
node-npmtest-npm/node_modules/npm/node_modules/which/ 12.35% (10 / 81) 6.06% (4 / 66) 0% (0 / 7) 12.5% (10 / 80)
node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/ 28.3% (15 / 53) 6.12% (3 / 49) 0% (0 / 10) 28.3% (15 / 53)
node-npmtest-npm/node_modules/npm/node_modules/wrappy/ 36.84% (7 / 19) 40% (4 / 10) 25% (1 / 4) 38.89% (7 / 18)
node-npmtest-npm/node_modules/npm/node_modules/write-file-atomic/ 22.03% (13 / 59) 2.08% (1 / 48) 0% (0 / 9) 25% (13 / 52)
node-npmtest-npm/node_modules/npm/scripts/ 16.67% (9 / 54) 6.25% (2 / 32) 0% (0 / 5) 17.31% (9 / 52)
Code coverage report for node-npmtest-npm/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/

Statements: 100% (153 / 153)      Branches: 100% (126 / 126)      Functions: 100% (28 / 28)      Lines: 100% (153 / 153)      Ignored: 26 statements, 1 function, 30 branches     

All files » node-npmtest-npm/
File Statements Branches Functions Lines
example.js 100% (83 / 83) 100% (73 / 73) 100% (12 / 12) 100% (83 / 83)
lib.npmtest_npm.js 100% (16 / 16) 100% (14 / 14) 100% (3 / 3) 100% (16 / 16)
test.js 100% (54 / 54) 100% (39 / 39) 100% (13 / 13) 100% (54 / 54)
Code coverage report for node-npmtest-npm/example.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/example.js

Statements: 100% (83 / 83)      Branches: 100% (73 / 73)      Functions: 100% (12 / 12)      Lines: 100% (83 / 83)      Ignored: 26 statements, 1 function, 30 branches     

All files » node-npmtest-npm/ » example.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328                                                  2   2         2   2   2 2 2         1             2       2       2   2               1 2           2     2     2 2   1       2     1 1 1   1 1     1 1   1     1   2           1   1   1         1 2 2 3 3 3 3 1     3 3         3       1 3 1       1 1               1   1 1 1   1   1                                                                                                                                                                                       1 1                       1     6 6   1   2   1   2         1 1   1         1             1     1 1     1 1   1 1 1 1 1 1 1   1 1   1        
/*
example.js
 
quickstart example
 
instruction
    1. save this script as example.js
    2. run the shell command:
        $ npm install npmtest-npm && PORT=8081 node example.js
    3. play with the browser-demo on http://127.0.0.1:8081
*/
 
 
 
/* istanbul instrument in package npmtest_npm */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || (local.modeJs === 'browser'
            ? local.global.utility2_npmtest_npm
            : global.utility2_moduleExports);
        // export local
        local.global.local = local;
    }());
    switch (local.modeJs) {
 
 
 
    // post-init
    // run browser js-env code - post-init
    /* istanbul ignore next */
    case 'browser':
        local.testRunBrowser = function (event) {
            Eif (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('onreset'))) {
                // reset output
                Array.from(
                    document.querySelectorAll('body > .resettable')
                ).forEach(function (element) {
                    switch (element.tagName) {
                    case 'INPUT':
                    case 'TEXTAREA':
                        element.value = '';
                        break;
                    default:
                        element.textContent = '';
                    }
                });
            }
            switch (event && event.currentTarget && event.currentTarget.id) {
            case 'testRunButton1':
                // show tests
                Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
                    document.querySelector('#testReportDiv1').style.display = 'block';
                    document.querySelector('#testRunButton1').textContent =
                        'hide internal test';
                    local.modeTest = true;
                    local.testRunDefault(local);
                // hide tests
                } else {
                    document.querySelector('#testReportDiv1').style.display = 'none';
                    document.querySelector('#testRunButton1').textContent = 'run internal test';
                }
                break;
            // custom-case
            default:
                break;
            }
            Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('oneval')))) {
                // try to eval input-code
                try {
                    /*jslint evil: true*/
                    eval(document.querySelector('#inputTextareaEval1').value);
                } catch (errorCaught) {
                    console.error(errorCaught);
                }
            }
        };
        // log stderr and stdout to #outputTextareaStdout1
        ['error', 'log'].forEach(function (key) {
            console[key + '_original'] = console[key];
            console[key] = function () {
                var element;
                console[key + '_original'].apply(console, arguments);
                element = document.querySelector('#outputTextareaStdout1');
                Iif (!element) {
                    return;
                }
                // append text to #outputTextareaStdout1
                element.value += Array.from(arguments).map(function (arg) {
                    return typeof arg === 'string'
                        ? arg
                        : JSON.stringify(arg, null, 4);
                }).join(' ') + '\n';
                // scroll textarea to bottom
                element.scrollTop = element.scrollHeight;
            };
        });
        // init event-handling
        ['change', 'click', 'keyup'].forEach(function (event) {
            Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
                element.addEventListener(event, local.testRunBrowser);
            });
        });
        // run tests
        local.testRunBrowser();
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        // export local
        module.exports = local;
        // require modules
        local.fs = require('fs');
        local.http = require('http');
        local.url = require('url');
        // init assets
        local.assetsDict = local.assetsDict || {};
        /* jslint-ignore-begin */
        local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
    box-sizing: false,\n\
    universal-selector: false\n\
*/\n\
* {\n\
    box-sizing: border-box;\n\
}\n\
body {\n\
    background: #dde;\n\
    font-family: Arial, Helvetica, sans-serif;\n\
    margin: 2rem;\n\
}\n\
body > * {\n\
    margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
    margin-top: 20px;\n\
    text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
    font-family: monospace;\n\
    height: 10rem;\n\
    width: 100%;\n\
}\n\
textarea[readonly] {\n\
    background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
    <a\n\
        {{#if env.npm_package_homepage}}\n\
        href="{{env.npm_package_homepage}}"\n\
        {{/if env.npm_package_homepage}}\n\
        target="_blank"\n\
    >\n\
utility2-comment -->\n\
        {{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
    </a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_npm.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
    [ this app was created with\n\
    <a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
    ]\n\
</div>\n\
</body>\n\
</html>\n\
';
        /* jslint-ignore-end */
        Iif (local.templateRender) {
            local.assetsDict['/'] = local.templateRender(
                local.assetsDict['/assets.index.template.html'],
                {
                    env: local.objectSetDefault(local.env, {
                        npm_package_description: 'the greatest app in the world!',
                        npm_package_name: 'my-app',
                        npm_package_nameAlias: 'my_app',
                        npm_package_version: '0.0.1'
                    })
                }
            );
        } else {
            local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
                .replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
                    // jslint-hack
                    String(match0);
                    switch (match1) {
                    case 'npm_package_description':
                        return 'the greatest app in the world!';
                    case 'npm_package_name':
                        return 'my-app';
                    case 'npm_package_nameAlias':
                        return 'my_app';
                    case 'npm_package_version':
                        return '0.0.1';
                    }
                });
        }
        // run the cli
        Eif (local.global.utility2_rollup || module !== require.main) {
            break;
        }
        local.assetsDict['/assets.example.js'] =
            local.assetsDict['/assets.example.js'] ||
            local.fs.readFileSync(__filename, 'utf8');
        // bug-workaround - long $npm_package_buildCustomOrg
        /* jslint-ignore-begin */
        local.assetsDict['/assets.npmtest_npm.rollup.js'] =
            local.assetsDict['/assets.npmtest_npm.rollup.js'] ||
            local.fs.readFileSync(
                local.npmtest_npm.__dirname + '/lib.npmtest_npm.js',
                'utf8'
            ).replace((/^#!/), '//');
        /* jslint-ignore-end */
        local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
        // if $npm_config_timeout_exit exists,
        // then exit this process after $npm_config_timeout_exit ms
        if (Number(process.env.npm_config_timeout_exit)) {
            setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
        }
        // start server
        if (local.global.utility2_serverHttp1) {
            break;
        }
        process.env.PORT = process.env.PORT || '8081';
        console.error('server starting on port ' + process.env.PORT);
        local.http.createServer(function (request, response) {
            request.urlParsed = local.url.parse(request.url);
            if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
                response.end(local.assetsDict[request.urlParsed.pathname]);
                return;
            }
            response.statusCode = 404;
            response.end();
        }).listen(process.env.PORT);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-npm/lib.npmtest_npm.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/lib.npmtest_npm.js

Statements: 100% (16 / 16)      Branches: 100% (14 / 14)      Functions: 100% (3 / 3)      Lines: 100% (16 / 16)      Ignored: none     

All files » node-npmtest-npm/ » lib.npmtest_npm.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                      2   2         2   2   2 2 2         1             2       2   2   2 1   1 1 1          
/* istanbul instrument in package npmtest_npm */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || local;
        // init lib
        local.local = local.npmtest_npm = local;
        // init exports
        if (local.modeJs === 'browser') {
            local.global.utility2_npmtest_npm = local;
        } else {
            module.exports = local;
            module.exports.__dirname = __dirname;
            module.exports.module = module;
        }
    }());
}());
 
 
Code coverage report for node-npmtest-npm/test.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/test.js

Statements: 100% (54 / 54)      Branches: 100% (39 / 39)      Functions: 100% (13 / 13)      Lines: 100% (54 / 54)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                      2   2         2   2   2 2 2         1             2     2     1       1     1   1     2           2 2   2           1           1           2 2   2           1             1       1     1             1             1 1     1             1 1 1 1 1 1     1         2 2     1             2 2     1             2 2     1             2 2     1             1 1       1 1        
/* istanbul instrument in package npmtest_npm */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        switch (local.modeJs) {
        // re-init local from window.local
        case 'browser':
            local = local.global.utility2.objectSetDefault(
                local.global.utility2_rollup || local.global.local,
                local.global.utility2
            );
            break;
        // re-init local from example.js
        case 'node':
            local = (local.global.utility2_rollup || require('utility2'))
                .requireExampleJsFromReadme();
            break;
        }
        // export local
        local.global.local = local;
    }());
 
 
 
    // run shared js-env code - function
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - function
    case 'browser':
        break;
 
 
 
    // run node js-env code - function
    case 'node':
        break;
    }
 
 
 
    // run shared js-env code - post-init
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - post-init
    case 'browser':
        local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
            options,
            onError
        ) {
        /*
         * this function will test browsers's null-case handling-behavior-behavior
         */
            onError(null, options);
        };
 
        // run tests
        local.nop(local.modeTest &&
            document.querySelector('#testRunButton1') &&
            document.querySelector('#testRunButton1').click());
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApidoc's default handling-behavior-behavior
         */
            options = { modulePathList: module.paths };
            local.buildApidoc(options, onError);
        };
 
        local.testCase_buildApp_default = local.testCase_buildApp_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApp's default handling-behavior-behavior
         */
            local.testCase_buildReadme_default(options, local.onErrorThrow);
            local.testCase_buildLib_default(options, local.onErrorThrow);
            local.testCase_buildTest_default(options, local.onErrorThrow);
            local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
            options = [];
            local.buildApp(options, onError);
        };
 
        local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
            function (options, onError) {
            /*
             * this function will test buildCustomOrg's default handling-behavior
             */
                options = {};
                local.buildCustomOrg(options, onError);
            };
 
        local.testCase_buildLib_default = local.testCase_buildLib_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildLib's default handling-behavior
         */
            options = {};
            local.buildLib(options, onError);
        };
 
        local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildReadme's default handling-behavior-behavior
         */
            options = {};
            local.buildReadme(options, onError);
        };
 
        local.testCase_buildTest_default = local.testCase_buildTest_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildTest's default handling-behavior
         */
            options = {};
            local.buildTest(options, onError);
        };
 
        local.testCase_webpage_default = local.testCase_webpage_default || function (
            options,
            onError
        ) {
        /*
         * this function will test webpage's default handling-behavior
         */
            options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
            local.browserTest(options, onError);
        };
 
        // run test-server
        local.testRunServer(local);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/

Statements: 16.64% (787 / 4729)      Branches: 0.51% (13 / 2559)      Functions: 2.07% (15 / 724)      Lines: 18.46% (785 / 4252)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/
File Statements Branches Functions Lines
access.js 20.59% (14 / 68) 0% (0 / 42) 0% (0 / 10) 21.88% (14 / 64)
adduser.js 29.03% (9 / 31) 0% (0 / 12) 0% (0 / 2) 32.14% (9 / 28)
bugs.js 31.58% (6 / 19) 0% (0 / 10) 0% (0 / 3) 33.33% (6 / 18)
build.js 19.08% (29 / 152) 0% (0 / 109) 0% (0 / 27) 21.32% (29 / 136)
cache.js 15.79% (30 / 190) 0% (0 / 108) 0% (0 / 26) 18.07% (30 / 166)
completion.js 18.06% (26 / 144) 0% (0 / 63) 4.17% (1 / 24) 20.16% (26 / 129)
config.js 13.13% (26 / 198) 0% (0 / 124) 0% (0 / 22) 14.61% (26 / 178)
dedupe.js 18.75% (18 / 96) 0% (0 / 20) 0% (0 / 18) 20% (18 / 90)
deprecate.js 21.21% (7 / 33) 0% (0 / 16) 0% (0 / 5) 26.92% (7 / 26)
doctor.js 23.75% (19 / 80) 0% (0 / 44) 0% (0 / 6) 27.54% (19 / 69)
edit.js 37.5% (9 / 24) 0% (0 / 10) 0% (0 / 3) 42.86% (9 / 21)
explore.js 32.43% (12 / 37) 0% (0 / 16) 0% (0 / 3) 34.29% (12 / 35)
fetch-package-metadata.js 14% (35 / 250) 0% (0 / 99) 0% (0 / 41) 15.22% (35 / 230)
get.js 83.33% (5 / 6) 100% (0 / 0) 0% (0 / 1) 83.33% (5 / 6)
help-search.js 10.57% (13 / 123) 0% (0 / 74) 0% (0 / 20) 11.71% (13 / 111)
help.js 14.08% (20 / 142) 0% (0 / 63) 0% (0 / 22) 14.93% (20 / 134)
init.js 38.1% (8 / 21) 0% (0 / 6) 0% (0 / 2) 38.1% (8 / 21)
install.js 6.25% (28 / 448) 0% (0 / 158) 0% (0 / 89) 6.75% (28 / 415)
link.js 18.7% (23 / 123) 0% (0 / 65) 0% (0 / 22) 20.54% (23 / 112)
logout.js 29.63% (8 / 27) 0% (0 / 12) 0% (0 / 4) 33.33% (8 / 24)
ls.js 8.41% (29 / 345) 0.33% (1 / 299) 0% (0 / 31) 9.32% (29 / 311)
npm.js 30.51% (83 / 272) 8.63% (12 / 139) 34.15% (14 / 41) 32.93% (81 / 246)
outdated.js 12.2% (30 / 246) 0% (0 / 171) 0% (0 / 39) 13.7% (30 / 219)
owner.js 8.89% (16 / 180) 0% (0 / 114) 0% (0 / 32) 10.26% (16 / 156)
pack.js 11.76% (6 / 51) 0% (0 / 16) 0% (0 / 9) 13.64% (6 / 44)
ping.js 31.25% (5 / 16) 0% (0 / 8) 0% (0 / 2) 35.71% (5 / 14)
prefix.js 45.45% (5 / 11) 0% (0 / 4) 0% (0 / 1) 50% (5 / 10)
prune.js 28.57% (14 / 49) 0% (0 / 10) 0% (0 / 10) 32.56% (14 / 43)
publish.js 20.69% (18 / 87) 0% (0 / 52) 0% (0 / 9) 23.68% (18 / 76)
rebuild.js 20.31% (13 / 64) 0% (0 / 32) 0% (0 / 8) 24.53% (13 / 53)
repo.js 31.25% (10 / 32) 0% (0 / 16) 0% (0 / 5) 34.48% (10 / 29)
restart.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
root.js 45.45% (5 / 11) 0% (0 / 4) 0% (0 / 1) 50% (5 / 10)
run-script.js 12.82% (15 / 117) 0% (0 / 88) 0% (0 / 17) 14.42% (15 / 104)
search.js 24.56% (14 / 57) 0% (0 / 19) 0% (0 / 15) 25.93% (14 / 54)
set.js 62.5% (5 / 8) 0% (0 / 2) 0% (0 / 1) 71.43% (5 / 7)
shrinkwrap.js 15.79% (21 / 133) 0% (0 / 66) 0% (0 / 23) 17.8% (21 / 118)
star.js 35.71% (10 / 28) 0% (0 / 12) 0% (0 / 5) 40% (10 / 25)
stars.js 27.59% (8 / 29) 0% (0 / 16) 0% (0 / 5) 30.77% (8 / 26)
start.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
stop.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
substack.js 45.45% (5 / 11) 0% (0 / 2) 0% (0 / 1) 50% (5 / 10)
team.js 33.33% (8 / 24) 0% (0 / 16) 0% (0 / 4) 34.78% (8 / 23)
unbuild.js 29.33% (22 / 75) 0% (0 / 36) 0% (0 / 14) 30.99% (22 / 71)
uninstall.js 21.15% (11 / 52) 0% (0 / 17) 0% (0 / 9) 23.91% (11 / 46)
unpublish.js 16.67% (14 / 84) 0% (0 / 49) 0% (0 / 14) 20% (14 / 70)
update.js 20% (7 / 35) 0% (0 / 19) 0% (0 / 6) 22.58% (7 / 31)
version.js 16.28% (28 / 172) 0% (0 / 87) 0% (0 / 32) 18.42% (28 / 152)
view.js 9.48% (22 / 232) 0% (0 / 184) 0% (0 / 30) 10.58% (22 / 208)
visnup.js 41.67% (5 / 12) 0% (0 / 4) 0% (0 / 3) 45.45% (5 / 11)
whoami.js 16.13% (5 / 31) 0% (0 / 18) 0% (0 / 2) 18.52% (5 / 27)
xmas.js 10% (5 / 50) 0% (0 / 8) 0% (0 / 5) 11.9% (5 / 42)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/access.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/access.js

Statements: 20.59% (14 / 68)      Branches: 0% (0 / 42)      Functions: 0% (0 / 10)      Lines: 21.88% (14 / 64)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131    1   1 1 1 1   1   1   1                 1     1                                                   1                 1                               1                                                                 1                                          
'use strict'
 
var resolve = require('path').resolve
 
var readPackageJson = require('read-package-json')
var mapToRegistry = require('./utils/map-to-registry.js')
var npm = require('./npm.js')
var output = require('./utils/output.js')
 
var whoami = require('./whoami')
 
module.exports = access
 
access.usage =
  'npm access public [<package>]\n' +
  'npm access restricted [<package>]\n' +
  'npm access grant <read-only|read-write> <scope:team> [<package>]\n' +
  'npm access revoke <scope:team> [<package>]\n' +
  'npm access ls-packages [<user>|<scope>|<scope:team>]\n' +
  'npm access ls-collaborators [<package> [<user>]]\n' +
  'npm access edit [<package>]'
 
access.subcommands = ['public', 'restricted', 'grant', 'revoke',
                      'ls-packages', 'ls-collaborators', 'edit']
 
access.completion = function (opts, cb) {
  var argv = opts.conf.argv.remain
  if (argv.length === 2) {
    return cb(null, access.subcommands)
  }
 
  switch (argv[2]) {
    case 'grant':
      if (argv.length === 3) {
        return cb(null, ['read-only', 'read-write'])
      } else {
        return cb(null, [])
      }
    case 'public':
    case 'restricted':
    case 'ls-packages':
    case 'ls-collaborators':
    case 'edit':
      return cb(null, [])
    case 'revoke':
      return cb(null, [])
    default:
      return cb(new Error(argv[2] + ' not recognized'))
  }
}
 
function access (args, cb) {
  var cmd = args.shift()
  var params
  return parseParams(cmd, args, function (err, p) {
    if (err) { return cb(err) }
    params = p
    return mapToRegistry(params.package, npm.config, invokeCmd)
  })
 
  function invokeCmd (err, uri, auth, base) {
    if (err) { return cb(err) }
    params.auth = auth
    try {
      return npm.registry.access(cmd, uri, params, function (err, data) {
        if (!err && data) {
          output(JSON.stringify(data, undefined, 2))
        }
        cb(err, data)
      })
    } catch (e) {
      cb(e.message + '\n\nUsage:\n' + access.usage)
    }
  }
}
 
function parseParams (cmd, args, cb) {
  // mapToRegistry will complain if package is undefined,
  // but it's not needed for ls-packages
  var params = { 'package': '' }
  if (cmd === 'grant') {
    params.permissions = args.shift()
  }
  if (['grant', 'revoke', 'ls-packages'].indexOf(cmd) !== -1) {
    var entity = (args.shift() || '').split(':')
    params.scope = entity[0]
    params.team = entity[1]
  }
 
  if (cmd === 'ls-packages') {
    if (!params.scope) {
      whoami([], true, function (err, scope) {
        params.scope = scope
        cb(err, params)
      })
    } else {
      cb(null, params)
    }
  } else {
    getPackage(args.shift(), function (err, pkg) {
      if (err) return cb(err)
      params.package = pkg
 
      if (cmd === 'ls-collaborators') params.user = args.shift()
      cb(null, params)
    })
  }
}
 
function getPackage (name, cb) {
  if (name && name.trim()) {
    cb(null, name.trim())
  } else {
    readPackageJson(
      resolve(npm.prefix, 'package.json'),
      function (err, data) {
        if (err) {
          if (err.code === 'ENOENT') {
            cb(new Error('no package name passed to command and no package.json found'))
          } else {
            cb(err)
          }
        } else {
          cb(null, data.name)
        }
      }
    )
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/adduser.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/adduser.js

Statements: 29.03% (9 / 31)      Branches: 0% (0 / 12)      Functions: 0% (0 / 2)      Lines: 32.14% (9 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 511   1 1 1 1   1 1     1         1                                                                    
module.exports = adduser
 
var log = require('npmlog')
var npm = require('./npm.js')
var usage = require('./utils/usage')
var crypto
 
try {
  crypto = require('crypto')
} catch (ex) {}
 
adduser.usage = usage(
  'adduser',
  'npm adduser [--registry=url] [--scope=@orgname] [--auth-type=legacy] [--always-auth]'
)
 
function adduser (args, cb) {
  if (!crypto) {
    return cb(new Error(
    'You must compile node with ssl support to use the adduser feature'
    ))
  }
 
  var registry = npm.config.get('registry')
  var scope = npm.config.get('scope')
  var creds = npm.config.getCredentialsByURI(npm.config.get('registry'))
 
  if (scope) {
    var scopedRegistry = npm.config.get(scope + ':registry')
    var cliRegistry = npm.config.get('registry', 'cli')
    if (scopedRegistry && !cliRegistry) registry = scopedRegistry
  }
 
  log.disableProgress()
 
  try {
    var auth = require('./auth/' + npm.config.get('auth-type'))
  } catch (e) {
    return cb(new Error('no such auth module'))
  }
  auth.login(creds, registry, scope, function (err, newCreds) {
    if (err) return cb(err)
 
    npm.config.del('_token', 'user') // prevent legacy pollution
    if (scope) npm.config.set(scope + ':registry', registry, 'user')
    npm.config.setCredentialsByURI(registry, newCreds)
    npm.config.save('user', cb)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/bugs.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/bugs.js

Statements: 31.58% (6 / 19)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 33.33% (6 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 342   2 2 2 2                           1                            
module.exports = bugs
 
var npm = require('./npm.js')
var log = require('npmlog')
var opener = require('opener')
var fetchPackageMetadata = require('./fetch-package-metadata.js')
var usage = require('./utils/usage')
 
bugs.usage = usage(
  'bugs',
  'npm bugs [<pkgname>]'
)
 
bugs.completion = function (opts, cb) {
  // FIXME: there used to be registry completion here, but it stopped making
  // sense somewhere around 50,000 packages on the registry
  cb()
}
 
function bugs (args, cb) {
  var n = args.length ? args[0] : '.'
  fetchPackageMetadata(n, '.', {fullMetadata: true}, function (er, d) {
    if (er) return cb(er)
 
    var url = d.bugs && ((typeof d.bugs === 'string') ? d.bugs : d.bugs.url)
    if (!url) {
      url = 'https://www.npmjs.org/package/' + d.name
    }
    log.silly('bugs', 'url', url)
    opener(url, { command: npm.config.get('browser') }, cb)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/build.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/build.js

Statements: 19.08% (29 / 152)      Branches: 0% (0 / 109)      Functions: 0% (0 / 27)      Lines: 21.32% (29 / 136)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268                  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1 1   1 1 1                                               1                                       1                                 1                                                           1                                                     1                                                                         1                                                                     1               1                                                                            
// npm build command
 
// everything about the installation after the creation of
// the .npm/{name}/{version}/package folder.
// linking the modules into the npm.root,
// resolving dependencies, etc.
 
// This runs AFTER install or link are completed.
 
var npm = require('./npm.js')
var log = require('npmlog')
var chain = require('slide').chain
var fs = require('graceful-fs')
var path = require('path')
var lifecycle = require('./utils/lifecycle.js')
var readJson = require('read-package-json')
var link = require('./utils/link.js')
var linkIfExists = link.ifExists
var cmdShim = require('cmd-shim')
var cmdShimIfExists = cmdShim.ifExists
var asyncMap = require('slide').asyncMap
var ini = require('ini')
var writeFile = require('write-file-atomic')
var packageId = require('./utils/package-id.js')
var output = require('./utils/output.js')
 
module.exports = build
build.usage = 'npm build [<folder>]'
 
build._didBuild = {}
build._noLC = {}
function build (args, global, didPre, didRB, cb) {
  if (typeof cb !== 'function') {
    cb = didRB
    didRB = false
  }
  if (typeof cb !== 'function') {
    cb = didPre
    didPre = false
  }
  if (typeof cb !== 'function') {
    cb = global
    global = npm.config.get('global')
  }
 
  // it'd be nice to asyncMap these, but actually, doing them
  // in parallel generally munges up the output from node-waf
  var builder = build_(global, didPre, didRB)
  chain(args.map(function (arg) {
    return function (cb) {
      builder(arg, cb)
    }
  }), cb)
}
 
function build_ (global, didPre, didRB) {
  return function (folder, cb) {
    folder = path.resolve(folder)
    if (build._didBuild[folder]) log.info('build', 'already built', folder)
    build._didBuild[folder] = true
    log.info('build', folder)
    readJson(path.resolve(folder, 'package.json'), function (er, pkg) {
      if (er) return cb(er)
      chain([
        !didPre && [lifecycle, pkg, 'preinstall', folder],
        [linkStuff, pkg, folder, global, didRB],
        [writeBuiltinConf, pkg, folder],
        didPre !== build._noLC && [lifecycle, pkg, 'install', folder],
        didPre !== build._noLC && [lifecycle, pkg, 'postinstall', folder]
      ],
      cb)
    })
  }
}
 
var writeBuiltinConf = build.writeBuiltinConf = function (pkg, folder, cb) {
  // the builtin config is "sticky". Any time npm installs
  // itself globally, it puts its builtin config file there
  var parent = path.dirname(folder)
  var dir = npm.globalDir
 
  if (pkg.name !== 'npm' ||
      !npm.config.get('global') ||
      !npm.config.usingBuiltin ||
      dir !== parent) {
    return cb()
  }
 
  var data = ini.stringify(npm.config.sources.builtin.data)
  writeFile(path.resolve(folder, 'npmrc'), data, cb)
}
 
var linkStuff = build.linkStuff = function (pkg, folder, global, didRB, cb) {
  // allow to opt out of linking binaries.
  if (npm.config.get('bin-links') === false) return cb()
 
  // if it's global, and folder is in {prefix}/node_modules,
  // then bins are in {prefix}/bin
  // otherwise, then bins are in folder/../.bin
  var parent = pkg.name && pkg.name[0] === '@' ? path.dirname(path.dirname(folder)) : path.dirname(folder)
  var gnm = global && npm.globalDir
  var gtop = parent === gnm
 
  log.info('linkStuff', packageId(pkg))
  log.silly('linkStuff', packageId(pkg), 'has', parent, 'as its parent node_modules')
  if (global) log.silly('linkStuff', packageId(pkg), 'is part of a global install')
  if (gnm) log.silly('linkStuff', packageId(pkg), 'is installed into a global node_modules')
  if (gtop) log.silly('linkStuff', packageId(pkg), 'is installed into the top-level global node_modules')
 
  shouldWarn(pkg, folder, global, function () {
    asyncMap(
      [linkBins, linkMans, !didRB && rebuildBundles],
      function (fn, cb) {
        if (!fn) return cb()
        log.verbose(fn.name, packageId(pkg))
        fn(pkg, folder, parent, gtop, cb)
      },
      cb
    )
  })
}
 
function shouldWarn (pkg, folder, global, cb) {
  var parent = path.dirname(folder)
  var top = parent === npm.dir
  var cwd = npm.localPrefix
 
  readJson(path.resolve(cwd, 'package.json'), function (er, topPkg) {
    if (er) return cb(er)
 
    var linkedPkg = path.basename(cwd)
    var currentPkg = path.basename(folder)
 
    // current searched package is the linked package on first call
    if (linkedPkg !== currentPkg) {
      // don't generate a warning if it's listed in dependencies
      if (Object.keys(topPkg.dependencies || {})
          .concat(Object.keys(topPkg.devDependencies || {}))
          .indexOf(currentPkg) === -1) {
        if (top && pkg.preferGlobal && !global) {
          log.warn('prefer global', packageId(pkg) + ' should be installed with -g')
        }
      }
    }
 
    cb()
  })
}
 
function rebuildBundles (pkg, folder, parent, gtop, cb) {
  if (!npm.config.get('rebuild-bundle')) return cb()
 
  var deps = Object.keys(pkg.dependencies || {})
             .concat(Object.keys(pkg.devDependencies || {}))
  var bundles = pkg.bundleDependencies || pkg.bundledDependencies || []
 
  fs.readdir(path.resolve(folder, 'node_modules'), function (er, files) {
    // error means no bundles
    if (er) return cb()
 
    log.verbose('rebuildBundles', files)
    // don't asyncMap these, because otherwise build script output
    // gets interleaved and is impossible to read
    chain(files.filter(function (file) {
      // rebuild if:
      // not a .folder, like .bin or .hooks
      return !file.match(/^[\._-]/) &&
          // not some old 0.x style bundle
          file.indexOf('@') === -1 &&
          // either not a dep, or explicitly bundled
          (deps.indexOf(file) === -1 || bundles.indexOf(file) !== -1)
    }).map(function (file) {
      file = path.resolve(folder, 'node_modules', file)
      return function (cb) {
        if (build._didBuild[file]) return cb()
        log.verbose('rebuild bundle', file)
        // if file is not a package dir, then don't do it.
        fs.lstat(path.resolve(file, 'package.json'), function (er) {
          if (er) return cb()
          build_(false)(file, cb)
        })
      }
    }), cb)
  })
}
 
function linkBins (pkg, folder, parent, gtop, cb) {
  if (!pkg.bin || !gtop && path.basename(parent) !== 'node_modules') {
    return cb()
  }
  var binRoot = gtop ? npm.globalBin
                     : path.resolve(parent, '.bin')
  log.verbose('linkBins', [pkg.bin, binRoot, gtop])
 
  asyncMap(Object.keys(pkg.bin), function (b, cb) {
    linkBin(
      path.resolve(folder, pkg.bin[b]),
      path.resolve(binRoot, b),
      gtop && folder,
      function (er) {
        if (er) return cb(er)
        // bins should always be executable.
        // XXX skip chmod on windows?
        var src = path.resolve(folder, pkg.bin[b])
        fs.chmod(src, npm.modes.exec, function (er) {
          if (er && er.code === 'ENOENT' && npm.config.get('ignore-scripts')) {
            return cb()
          }
          if (er || !gtop) return cb(er)
          var dest = path.resolve(binRoot, b)
          var out = npm.config.get('parseable')
                  ? dest + '::' + src + ':BINFILE'
                  : dest + ' -> ' + src
          output(out)
          cb()
        })
      }
    )
  }, cb)
}
 
function linkBin (from, to, gently, cb) {
  if (process.platform !== 'win32') {
    return linkIfExists(from, to, gently, cb)
  } else {
    return cmdShimIfExists(from, to, cb)
  }
}
 
function linkMans (pkg, folder, parent, gtop, cb) {
  if (!pkg.man || !gtop || process.platform === 'win32') return cb()
 
  var manRoot = path.resolve(npm.config.get('prefix'), 'share', 'man')
  log.verbose('linkMans', 'man files are', pkg.man, 'in', manRoot)
 
  // make sure that the mans are unique.
  // otherwise, if there are dupes, it'll fail with EEXIST
  var set = pkg.man.reduce(function (acc, man) {
    acc[path.basename(man)] = man
    return acc
  }, {})
  pkg.man = pkg.man.filter(function (man) {
    return set[path.basename(man)] === man
  })
 
  asyncMap(pkg.man, function (man, cb) {
    if (typeof man !== 'string') return cb()
    log.silly('linkMans', 'preparing to link', man)
    var parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/)
    if (!parseMan) {
      return cb(new Error(
        man + ' is not a valid name for a man file.  ' +
        'Man files must end with a number, ' +
        'and optionally a .gz suffix if they are compressed.'
      ))
    }
 
    var stem = parseMan[1]
    var sxn = parseMan[2]
    var bn = path.basename(stem)
    var manSrc = path.resolve(folder, man)
    var manDest = path.join(manRoot, 'man' + sxn, bn)
 
    linkIfExists(manSrc, manDest, gtop && folder, cb)
  }, cb)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache.js

Statements: 15.79% (30 / 190)      Branches: 0% (0 / 108)      Functions: 0% (0 / 26)      Lines: 18.07% (30 / 166)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369                                                                                                                28   28 28 28   28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28                                                                           1                         1             1                                                 1                                     1                           1         1                                                                                   1                                                                                                                                   1                                                                       1                                                    
// XXX lib/utils/tar.js and this file need to be rewritten.
 
// URL-to-cache folder mapping:
// : -> !
// @ -> _
// http://registry.npmjs.org/foo/version -> cache/http!/...
//
 
/*
fetching a URL:
1. Check for URL in inflight URLs.  If present, add cb, and return.
2. Acquire lock at {cache}/{sha(url)}.lock
   retries = {cache-lock-retries, def=10}
   stale = {cache-lock-stale, def=60000}
   wait = {cache-lock-wait, def=10000}
3. if lock can't be acquired, then fail
4. fetch url, clear lock, call cbs
 
cache folders:
1. urls: http!/server.com/path/to/thing
2. c:\path\to\thing: file!/c!/path/to/thing
3. /path/to/thing: file!/path/to/thing
4. git@ private: git_github.com!npm/npm
5. git://public: git!/github.com/npm/npm
6. git+blah:// git-blah!/server.com/foo/bar
 
adding a folder:
1. tar into tmp/random/package.tgz
2. untar into tmp/random/contents/package, stripping one dir piece
3. tar tmp/random/contents/package to cache/n/v/package.tgz
4. untar cache/n/v/package.tgz into cache/n/v/package
5. rm tmp/random
 
Adding a url:
1. fetch to tmp/random/package.tgz
2. goto folder(2)
 
adding a name@version:
1. registry.get(name/version)
2. if response isn't 304, add url(dist.tarball)
 
adding a name@range:
1. registry.get(name)
2. Find a version that satisfies
3. add name@version
 
adding a local tarball:
1. untar to tmp/random/{blah}
2. goto folder(2)
 
adding a namespaced package:
1. lookup registry for @namespace
2. namespace_registry.get('name')
3. add url(namespace/latest.tarball)
*/
 
exports = module.exports = cache
 
cache.unpack = unpack
cache.clean = clean
cache.read = read
 
var npm = require('./npm.js')
var fs = require('graceful-fs')
var writeFileAtomic = require('write-file-atomic')
var assert = require('assert')
var rm = require('./utils/gently-rm.js')
var readJson = require('read-package-json')
var log = require('npmlog')
var path = require('path')
var asyncMap = require('slide').asyncMap
var tar = require('./utils/tar.js')
var fileCompletion = require('./utils/completion/file-completion.js')
var deprCheck = require('./utils/depr-check.js')
var addNamed = require('./cache/add-named.js')
var addLocal = require('./cache/add-local.js')
var addRemoteTarball = require('./cache/add-remote-tarball.js')
var addRemoteGit = require('./cache/add-remote-git.js')
var inflight = require('inflight')
var realizePackageSpecifier = require('realize-package-specifier')
var npa = require('npm-package-arg')
var getStat = require('./cache/get-stat.js')
var cachedPackageRoot = require('./cache/cached-package-root.js')
var mapToRegistry = require('./utils/map-to-registry.js')
var output = require('./utils/output.js')
 
cache.usage = 'npm cache add <tarball file>' +
              '\nnpm cache add <folder>' +
              '\nnpm cache add <tarball url>' +
              '\nnpm cache add <git url>' +
              '\nnpm cache add <name>@<version>' +
              '\nnpm cache ls [<path>]' +
              '\nnpm cache clean [<pkg>[@<version>]]'
 
cache.completion = function (opts, cb) {
  var argv = opts.conf.argv.remain
  if (argv.length === 2) {
    return cb(null, ['add', 'ls', 'clean'])
  }
 
  switch (argv[2]) {
    case 'clean':
    case 'ls':
      // cache and ls are easy, because the completion is
      // what ls_ returns anyway.
      // just get the partial words, minus the last path part
      var p = path.dirname(opts.partialWords.slice(3).join('/'))
      if (p === '.') p = ''
      return ls_(p, 2, cb)
    case 'add':
      // Same semantics as install and publish.
      return npm.commands.install.completion(opts, cb)
  }
}
 
function cache (args, cb) {
  var cmd = args.shift()
  switch (cmd) {
    case 'rm': case 'clear': case 'clean': return clean(args, cb)
    case 'list': case 'sl': case 'ls': return ls(args, cb)
    case 'add': return add(args, npm.prefix, cb)
    default: return cb('Usage: ' + cache.usage)
  }
}
 
// if the pkg and ver are in the cache, then
// just do a readJson and return.
// if they're not, then fetch them from the registry.
function read (name, ver, forceBypass, cb) {
  assert(typeof name === 'string', 'must include name of module to install')
  assert(typeof cb === 'function', 'must include callback')
 
  if (forceBypass === undefined || forceBypass === null) forceBypass = true
 
  var root = cachedPackageRoot({name: name, version: ver})
  function c (er, data) {
    if (er) log.verbose('cache', 'addNamed error for', name + '@' + ver, er)
    if (data) deprCheck(data)
 
    return cb(er, data)
  }
 
  if (forceBypass && npm.config.get('force')) {
    log.verbose('using force', 'skipping cache')
    return addNamed(name, ver, null, c)
  }
 
  readJson(path.join(root, 'package', 'package.json'), function (er, data) {
    if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
 
    if (data) {
      if (!data.name) return cb(new Error('No name provided'))
      if (!data.version) return cb(new Error('No version provided'))
    }
 
    if (er) return addNamed(name, ver, null, c)
    else c(er, data)
  })
}
 
function normalize (args) {
  var normalized = ''
  if (args.length > 0) {
    var a = npa(args[0])
    if (a.name) normalized = a.name
    if (a.rawSpec) normalized = [normalized, a.rawSpec].join('/')
    if (args.length > 1) normalized = [normalized].concat(args.slice(1)).join('/')
  }
 
  if (normalized.substr(-1) === '/') {
    normalized = normalized.substr(0, normalized.length - 1)
  }
  normalized = path.normalize(normalized)
  log.silly('ls', 'normalized', normalized)
 
  return normalized
}
 
// npm cache ls [<path>]
function ls (args, cb) {
  var prefix = npm.config.get('cache')
  if (prefix.indexOf(process.env.HOME) === 0) {
    prefix = '~' + prefix.substr(process.env.HOME.length)
  }
  ls_(normalize(args), npm.config.get('depth'), function (er, files) {
    output(files.map(function (f) {
      return path.join(prefix, f)
    }).join('\n').trim())
    cb(er, files)
  })
}
 
// Calls cb with list of cached pkgs matching show.
function ls_ (req, depth, cb) {
  return fileCompletion(npm.cache, req, depth, cb)
}
 
// npm cache clean [<path>]
function clean (args, cb) {
  assert(typeof cb === 'function', 'must include callback')
 
  if (!args) args = []
 
  var f = path.join(npm.cache, normalize(args))
  if (f === npm.cache) {
    fs.readdir(npm.cache, function (er, files) {
      if (er) return cb()
      asyncMap(
        files.filter(function (f) {
          return npm.config.get('force') || f !== '-'
        }).map(function (f) {
          return path.join(npm.cache, f)
        }),
        rm,
        cb
      )
    })
  } else {
    rm(f, cb)
  }
}
 
// npm cache add <tarball-url>
// npm cache add <pkg> <ver>
// npm cache add <tarball>
// npm cache add <folder>
cache.add = function (pkg, ver, where, scrub, cb) {
  assert(typeof pkg === 'string', 'must include name of package to install')
  assert(typeof cb === 'function', 'must include callback')
 
  if (scrub) {
    return clean([], function (er) {
      if (er) return cb(er)
      add([pkg, ver], where, cb)
    })
  }
  return add([pkg, ver], where, cb)
}
 
var adding = 0
function add (args, where, cb) {
  // this is hot code.  almost everything passes through here.
  // the args can be any of:
  // ['url']
  // ['pkg', 'version']
  // ['pkg@version']
  // ['pkg', 'url']
  // This is tricky, because urls can contain @
  // Also, in some cases we get [name, null] rather
  // that just a single argument.
 
  var usage = 'Usage:\n' +
              '    npm cache add <tarball-url>\n' +
              '    npm cache add <pkg>@<ver>\n' +
              '    npm cache add <tarball>\n' +
              '    npm cache add <folder>\n'
  var spec
 
  log.silly('cache add', 'args', args)
 
  if (args[1] === undefined) args[1] = null
 
  // at this point the args length must ==2
  if (args[1] !== null) {
    spec = args[0] + '@' + args[1]
  } else if (args.length === 2) {
    spec = args[0]
  }
 
  log.verbose('cache add', 'spec', spec)
 
  if (!spec) return cb(usage)
 
  adding++
  cb = afterAdd(cb)
 
  realizePackageSpecifier(spec, where, function (err, p) {
    if (err) return cb(err)
 
    log.silly('cache add', 'parsed spec', p)
 
    switch (p.type) {
      case 'local':
      case 'directory':
        addLocal(p, null, cb)
        break
      case 'remote':
        // get auth, if possible
        mapToRegistry(p.raw, npm.config, function (err, uri, auth) {
          if (err) return cb(err)
 
          addRemoteTarball(p.spec, { name: p.name }, null, auth, cb)
        })
        break
      case 'git':
      case 'hosted':
        addRemoteGit(p.rawSpec, cb)
        break
      default:
        if (p.name) return addNamed(p.name, p.spec, null, cb)
 
        cb(new Error("couldn't figure out how to install " + spec))
    }
  })
}
 
function unpack (pkg, ver, unpackTarget, dMode, fMode, uid, gid, cb) {
  if (typeof cb !== 'function') {
    cb = gid
    gid = null
  }
  if (typeof cb !== 'function') {
    cb = uid
    uid = null
  }
  if (typeof cb !== 'function') {
    cb = fMode
    fMode = null
  }
  if (typeof cb !== 'function') {
    cb = dMode
    dMode = null
  }
 
  read(pkg, ver, false, function (er) {
    if (er) {
      log.error('unpack', 'Could not read data for %s', pkg + '@' + ver)
      return cb(er)
    }
    npm.commands.unbuild([unpackTarget], true, function (er) {
      if (er) return cb(er)
      tar.unpack(
        path.join(cachedPackageRoot({ name: pkg, version: ver }), 'package.tgz'),
        unpackTarget,
        dMode, fMode,
        uid, gid,
        cb
      )
    })
  })
}
 
function afterAdd (cb) {
  return function (er, data) {
    adding--
 
    if (er || !data || !data.name || !data.version) return cb(er, data)
    log.silly('cache', 'afterAdd', data.name + '@' + data.version)
 
    // Save the resolved, shasum, etc. into the data so that the next
    // time we load from this cached data, we have all the same info.
    // Ignore if it fails.
    var pj = path.join(cachedPackageRoot(data), 'package', 'package.json')
 
    var done = inflight(pj, cb)
    if (!done) return log.verbose('afterAdd', pj, 'already in flight; not writing')
    log.verbose('afterAdd', pj, 'not in flight; writing')
 
    getStat(function (er, cs) {
      if (er) return done(er)
      writeFileAtomic(pj, JSON.stringify(data), { chown: cs }, function (er) {
        if (!er) log.verbose('afterAdd', pj, 'written')
        return done(null, data)
      })
    })
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/completion.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/completion.js

Statements: 18.06% (26 / 144)      Branches: 0% (0 / 63)      Functions: 4.17% (1 / 24)      Lines: 20.16% (26 / 129)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 2501   1   1 1 1 1 1 1 1 102 1 1 1 1 1   1                             1                           1                                                                                                                                                                                           1                                                             1         1                     1                                                 1                                 1           1                 1        
module.exports = completion
 
completion.usage = 'source <(npm completion)'
 
var npm = require('./npm.js')
var npmconf = require('./config/core.js')
var configDefs = npmconf.defs
var configTypes = configDefs.types
var shorthands = configDefs.shorthands
var nopt = require('nopt')
var configNames = Object.keys(configTypes)
  .filter(function (e) { return e.charAt(0) !== '_' })
var shorthandNames = Object.keys(shorthands)
var allConfs = configNames.concat(shorthandNames)
var once = require('once')
var isWindowsShell = require('./utils/is-windows-shell.js')
var output = require('./utils/output.js')
 
completion.completion = function (opts, cb) {
  if (opts.w > 3) return cb()
 
  var fs = require('graceful-fs')
  var path = require('path')
  var bashExists = null
  var zshExists = null
  fs.stat(path.resolve(process.env.HOME, '.bashrc'), function (er) {
    bashExists = !er
    next()
  })
  fs.stat(path.resolve(process.env.HOME, '.zshrc'), function (er) {
    zshExists = !er
    next()
  })
  function next () {
    if (zshExists === null || bashExists === null) return
    var out = []
    if (zshExists) out.push('~/.zshrc')
    if (bashExists) out.push('~/.bashrc')
    if (opts.w === 2) {
      out = out.map(function (m) {
        return ['>>', m]
      })
    }
    cb(null, out)
  }
}
 
function completion (args, cb) {
  if (isWindowsShell) {
    var e = new Error('npm completion supported only in MINGW / Git bash on Windows')
    e.code = 'ENOTSUP'
    e.errno = require('constants').ENOTSUP
    return cb(e)
  }
 
  // if the COMP_* isn't in the env, then just dump the script.
  if (process.env.COMP_CWORD === undefined ||
      process.env.COMP_LINE === undefined ||
      process.env.COMP_POINT === undefined) {
    return dumpScript(cb)
  }
 
  console.error(process.env.COMP_CWORD)
  console.error(process.env.COMP_LINE)
  console.error(process.env.COMP_POINT)
 
  // get the partial line and partial word,
  // if the point isn't at the end.
  // ie, tabbing at: npm foo b|ar
  var w = +process.env.COMP_CWORD
  var words = args.map(unescape)
  var word = words[w]
  var line = process.env.COMP_LINE
  var point = +process.env.COMP_POINT
  var partialLine = line.substr(0, point)
  var partialWords = words.slice(0, w)
 
  // figure out where in that last word the point is.
  var partialWord = args[w]
  var i = partialWord.length
  while (partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) {
    i--
  }
  partialWord = unescape(partialWord.substr(0, i))
  partialWords.push(partialWord)
 
  var opts = {
    words: words,
    w: w,
    word: word,
    line: line,
    lineLength: line.length,
    point: point,
    partialLine: partialLine,
    partialWords: partialWords,
    partialWord: partialWord,
    raw: args
  }
 
  cb = wrapCb(cb, opts)
 
  console.error(opts)
 
  if (partialWords.slice(0, -1).indexOf('--') === -1) {
    if (word.charAt(0) === '-') return configCompl(opts, cb)
    if (words[w - 1] &&
        words[w - 1].charAt(0) === '-' &&
        !isFlag(words[w - 1])) {
      // awaiting a value for a non-bool config.
      // don't even try to do this for now
      console.error('configValueCompl')
      return configValueCompl(opts, cb)
    }
  }
 
  // try to find the npm command.
  // it's the first thing after all the configs.
  // take a little shortcut and use npm's arg parsing logic.
  // don't have to worry about the last arg being implicitly
  // boolean'ed, since the last block will catch that.
  var parsed = opts.conf =
    nopt(configTypes, shorthands, partialWords.slice(0, -1), 0)
  // check if there's a command already.
  console.error(parsed)
  var cmd = parsed.argv.remain[1]
  if (!cmd) return cmdCompl(opts, cb)
 
  Object.keys(parsed).forEach(function (k) {
    npm.config.set(k, parsed[k])
  })
 
  // at this point, if words[1] is some kind of npm command,
  // then complete on it.
  // otherwise, do nothing
  cmd = npm.commands[cmd]
  if (cmd && cmd.completion) return cmd.completion(opts, cb)
 
  // nothing to do.
  cb()
}
 
function dumpScript (cb) {
  var fs = require('graceful-fs')
  var path = require('path')
  var p = path.resolve(__dirname, 'utils/completion.sh')
 
  // The Darwin patch below results in callbacks first for the write and then
  // for the error handler, so make sure we only call our callback once.
  cb = once(cb)
 
  fs.readFile(p, 'utf8', function (er, d) {
    if (er) return cb(er)
    d = d.replace(/^\#\!.*?\n/, '')
 
    process.stdout.write(d, function () { cb() })
    process.stdout.on('error', function (er) {
      // Darwin is a pain sometimes.
      //
      // This is necessary because the "source" or "." program in
      // bash on OS X closes its file argument before reading
      // from it, meaning that you get exactly 1 write, which will
      // work most of the time, and will always raise an EPIPE.
      //
      // Really, one should not be tossing away EPIPE errors, or any
      // errors, so casually.  But, without this, `. <(npm completion)`
      // can never ever work on OS X.
      if (er.errno === 'EPIPE') er = null
      cb(er)
    })
  })
}
 
function unescape (w) {
  if (w.charAt(0) === '\'') return w.replace(/^'|'$/g, '')
  else return w.replace(/\\ /g, ' ')
}
 
function escape (w) {
  if (!w.match(/\s+/)) return w
  return '\'' + w + '\''
}
 
// The command should respond with an array.  Loop over that,
// wrapping quotes around any that have spaces, and writing
// them to stdout.  Use console.log, not the outfd config.
// If any of the items are arrays, then join them with a space.
// Ie, returning ['a', 'b c', ['d', 'e']] would allow it to expand
// to: 'a', 'b c', or 'd' 'e'
function wrapCb (cb, opts) {
  return function (er, compls) {
    if (!Array.isArray(compls)) compls = compls ? [compls] : []
    compls = compls.map(function (c) {
      if (Array.isArray(c)) c = c.map(escape).join(' ')
      else c = escape(c)
      return c
    })
 
    if (opts.partialWord) {
      compls = compls.filter(function (c) {
        return c.indexOf(opts.partialWord) === 0
      })
    }
 
    console.error([er && er.stack, compls, opts.partialWord])
    if (er || compls.length === 0) return cb(er)
 
    output(compls.join('\n'))
    cb()
  }
}
 
// the current word has a dash.  Return the config names,
// with the same number of dashes as the current word has.
function configCompl (opts, cb) {
  var word = opts.word
  var split = word.match(/^(-+)((?:no-)*)(.*)$/)
  var dashes = split[1]
  var no = split[2]
  var flags = configNames.filter(isFlag)
  console.error(flags)
 
  return cb(null, allConfs.map(function (c) {
    return dashes + c
  }).concat(flags.map(function (f) {
    return dashes + (no || 'no-') + f
  })))
}
 
// expand with the valid values of various config values.
// not yet implemented.
function configValueCompl (opts, cb) {
  console.error('configValue', opts)
  return cb(null, [])
}
 
// check if the thing is a flag or not.
function isFlag (word) {
  // shorthands never take args.
  var split = word.match(/^(-*)((?:no-)+)?(.*)$/)
  var no = split[2]
  var conf = split[3]
  return no || configTypes[conf] === Boolean || shorthands[conf]
}
 
// complete against the npm commands
function cmdCompl (opts, cb) {
  return cb(null, npm.fullList)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config.js

Statements: 13.13% (26 / 198)      Branches: 0% (0 / 124)      Functions: 0% (0 / 22)      Lines: 14.61% (26 / 178)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 3071   1 1 1 1 1 1 1 1 1 1 1 1 1   1                   1                                                           1                       1                                                                                               1             1                                           1                     1       1           1       1                                                                                                                                                                                                                                                                       1        
module.exports = config
 
var log = require('npmlog')
var npm = require('./npm.js')
var npmconf = require('./config/core.js')
var fs = require('graceful-fs')
var writeFileAtomic = require('write-file-atomic')
var types = npmconf.defs.types
var ini = require('ini')
var editor = require('editor')
var os = require('os')
var umask = require('./utils/umask')
var usage = require('./utils/usage')
var output = require('./utils/output')
var noProgressTillDone = require('./utils/no-progress-while-running').tillDone
 
config.usage = usage(
  'config',
  'npm config set <key> <value>' +
  '\nnpm config get [<key>]' +
  '\nnpm config delete <key>' +
  '\nnpm config list' +
  '\nnpm config edit' +
  '\nnpm set <key> <value>' +
  '\nnpm get [<key>]'
)
config.completion = function (opts, cb) {
  var argv = opts.conf.argv.remain
  if (argv[1] !== 'config') argv.unshift('config')
  if (argv.length === 2) {
    var cmds = ['get', 'set', 'delete', 'ls', 'rm', 'edit']
    if (opts.partialWord !== 'l') cmds.push('list')
    return cb(null, cmds)
  }
 
  var action = argv[2]
  switch (action) {
    case 'set':
      // todo: complete with valid values, if possible.
      if (argv.length > 3) return cb(null, [])
      // fallthrough
      /*eslint no-fallthrough:0*/
    case 'get':
    case 'delete':
    case 'rm':
      return cb(null, Object.keys(types))
    case 'edit':
    case 'list': case 'ls':
      return cb(null, [])
    default: return cb(null, [])
  }
}
 
// npm config set key value
// npm config get key
// npm config list
function config (args, cb) {
  var action = args.shift()
  switch (action) {
    case 'set': return set(args[0], args[1], cb)
    case 'get': return get(args[0], cb)
    case 'delete': case 'rm': case 'del': return del(args[0], cb)
    case 'list': case 'ls': return list(cb)
    case 'edit': return edit(cb)
    default: return unknown(action, cb)
  }
}
 
function edit (cb) {
  var e = npm.config.get('editor')
  var which = npm.config.get('global') ? 'global' : 'user'
  var f = npm.config.get(which + 'config')
  if (!e) return cb(new Error('No EDITOR config or environ set.'))
  npm.config.save(which, function (er) {
    if (er) return cb(er)
    fs.readFile(f, 'utf8', function (er, data) {
      if (er) data = ''
      data = [
        ';;;;',
        '; npm ' + (npm.config.get('global')
                  ? 'globalconfig' : 'userconfig') + ' file',
        '; this is a simple ini-formatted file',
        '; lines that start with semi-colons are comments.',
        '; read `npm help config` for help on the various options',
        ';;;;',
        '',
        data
      ].concat([
        ';;;;',
        '; all options with default values',
        ';;;;'
      ]).concat(Object.keys(npmconf.defaults).reduce(function (arr, key) {
        var obj = {}
        obj[key] = npmconf.defaults[key]
        if (key === 'logstream') return arr
        return arr.concat(
          ini.stringify(obj)
            .replace(/\n$/m, '')
            .replace(/^/g, '; ')
            .replace(/\n/g, '\n; ')
            .split('\n'))
      }, []))
      .concat([''])
      .join(os.EOL)
      writeFileAtomic(
        f,
        data,
        function (er) {
          if (er) return cb(er)
          editor(f, { editor: e }, noProgressTillDone(cb))
        }
      )
    })
  })
}
 
function del (key, cb) {
  if (!key) return cb(new Error('no key provided'))
  var where = npm.config.get('global') ? 'global' : 'user'
  npm.config.del(key, where)
  npm.config.save(where, cb)
}
 
function set (key, val, cb) {
  if (key === undefined) {
    return unknown('', cb)
  }
  if (val === undefined) {
    if (key.indexOf('=') !== -1) {
      var k = key.split('=')
      key = k.shift()
      val = k.join('=')
    } else {
      val = ''
    }
  }
  key = key.trim()
  val = val.trim()
  log.info('config', 'set %j %j', key, val)
  var where = npm.config.get('global') ? 'global' : 'user'
  if (key.match(/umask/)) val = umask.fromString(val)
  npm.config.set(key, val, where)
  npm.config.save(where, cb)
}
 
function get (key, cb) {
  if (!key) return list(cb)
  if (!publicVar(key)) {
    return cb(new Error('---sekretz---'))
  }
  var val = npm.config.get(key)
  if (key.match(/umask/)) val = umask.toString(val)
  output(val)
  cb()
}
 
function sort (a, b) {
  return a > b ? 1 : -1
}
 
function publicVar (k) {
  return !(k.charAt(0) === '_' ||
           k.indexOf(':_') !== -1 ||
           types[k] !== types[k])
}
 
function getKeys (data) {
  return Object.keys(data).filter(publicVar).sort(sort)
}
 
function list (cb) {
  var msg = ''
  var long = npm.config.get('long')
 
  var cli = npm.config.sources.cli.data
  var cliKeys = getKeys(cli)
  if (cliKeys.length) {
    msg += '; cli configs\n'
    cliKeys.forEach(function (k) {
      if (cli[k] && typeof cli[k] === 'object') return
      if (k === 'argv') return
      msg += k + ' = ' + JSON.stringify(cli[k]) + '\n'
    })
    msg += '\n'
  }
 
  // env configs
  var env = npm.config.sources.env.data
  var envKeys = getKeys(env)
  if (envKeys.length) {
    msg += '; environment configs\n'
    envKeys.forEach(function (k) {
      if (env[k] !== npm.config.get(k)) {
        if (!long) return
        msg += '; ' + k + ' = ' +
          JSON.stringify(env[k]) + ' (overridden)\n'
      } else msg += k + ' = ' + JSON.stringify(env[k]) + '\n'
    })
    msg += '\n'
  }
 
  // project config file
  var project = npm.config.sources.project
  var pconf = project.data
  var ppath = project.path
  var pconfKeys = getKeys(pconf)
  if (pconfKeys.length) {
    msg += '; project config ' + ppath + '\n'
    pconfKeys.forEach(function (k) {
      var val = (k.charAt(0) === '_')
              ? '---sekretz---'
              : JSON.stringify(pconf[k])
      if (pconf[k] !== npm.config.get(k)) {
        if (!long) return
        msg += '; ' + k + ' = ' + val + ' (overridden)\n'
      } else msg += k + ' = ' + val + '\n'
    })
    msg += '\n'
  }
 
  // user config file
  var uconf = npm.config.sources.user.data
  var uconfKeys = getKeys(uconf)
  if (uconfKeys.length) {
    msg += '; userconfig ' + npm.config.get('userconfig') + '\n'
    uconfKeys.forEach(function (k) {
      var val = (k.charAt(0) === '_')
              ? '---sekretz---'
              : JSON.stringify(uconf[k])
      if (uconf[k] !== npm.config.get(k)) {
        if (!long) return
        msg += '; ' + k + ' = ' + val + ' (overridden)\n'
      } else msg += k + ' = ' + val + '\n'
    })
    msg += '\n'
  }
 
  // global config file
  var gconf = npm.config.sources.global.data
  var gconfKeys = getKeys(gconf)
  if (gconfKeys.length) {
    msg += '; globalconfig ' + npm.config.get('globalconfig') + '\n'
    gconfKeys.forEach(function (k) {
      var val = (k.charAt(0) === '_')
              ? '---sekretz---'
              : JSON.stringify(gconf[k])
      if (gconf[k] !== npm.config.get(k)) {
        if (!long) return
        msg += '; ' + k + ' = ' + val + ' (overridden)\n'
      } else msg += k + ' = ' + val + '\n'
    })
    msg += '\n'
  }
 
  // builtin config file
  var builtin = npm.config.sources.builtin || {}
  if (builtin && builtin.data) {
    var bconf = builtin.data
    var bpath = builtin.path
    var bconfKeys = getKeys(bconf)
    if (bconfKeys.length) {
      msg += '; builtin config ' + bpath + '\n'
      bconfKeys.forEach(function (k) {
        var val = (k.charAt(0) === '_')
                ? '---sekretz---'
                : JSON.stringify(bconf[k])
        if (bconf[k] !== npm.config.get(k)) {
          if (!long) return
          msg += '; ' + k + ' = ' + val + ' (overridden)\n'
        } else msg += k + ' = ' + val + '\n'
      })
      msg += '\n'
    }
  }
 
  // only show defaults if --long
  if (!long) {
    msg += '; node bin location = ' + process.execPath + '\n' +
           '; cwd = ' + process.cwd() + '\n' +
           '; HOME = ' + process.env.HOME + '\n' +
           '; "npm config ls -l" to show all defaults.\n'
 
    output(msg)
    return cb()
  }
 
  var defaults = npmconf.defaults
  var defKeys = getKeys(defaults)
  msg += '; default values\n'
  defKeys.forEach(function (k) {
    if (defaults[k] && typeof defaults[k] === 'object') return
    var val = JSON.stringify(defaults[k])
    if (defaults[k] !== npm.config.get(k)) {
      msg += '; ' + k + ' = ' + val + ' (overridden)\n'
    } else msg += k + ' = ' + val + '\n'
  })
  msg += '\n'
 
  output(msg)
  return cb()
}
 
function unknown (action, cb) {
  cb('Usage:\n' + config.usage)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/dedupe.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/dedupe.js

Statements: 18.75% (18 / 96)      Branches: 0% (0 / 20)      Functions: 0% (0 / 18)      Lines: 20% (18 / 90)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 1562 2 2 2 2 2 2 2 2 2                                           1                     1                                                                                             1                     1             1       1                   1       1                                                            
var util = require('util')
var path = require('path')
var validate = require('aproba')
var without = require('lodash.without')
var asyncMap = require('slide').asyncMap
var chain = require('slide').chain
var npa = require('npm-package-arg')
var log = require('npmlog')
var npm = require('./npm.js')
var Installer = require('./install.js').Installer
var findRequirement = require('./install/deps.js').findRequirement
var earliestInstallable = require('./install/deps.js').earliestInstallable
var checkPermissions = require('./install/check-permissions.js')
var decomposeActions = require('./install/decompose-actions.js')
var loadExtraneous = require('./install/deps.js').loadExtraneous
var filterInvalidActions = require('./install/filter-invalid-actions.js')
var recalculateMetadata = require('./install/deps.js').recalculateMetadata
var sortActions = require('./install/diff-trees.js').sortActions
var moduleName = require('./utils/module-name.js')
var packageId = require('./utils/package-id.js')
var childPath = require('./utils/child-path.js')
var usage = require('./utils/usage')
 
module.exports = dedupe
module.exports.Deduper = Deduper
 
dedupe.usage = usage(
  'dedupe',
  'npm dedupe'
)
 
function dedupe (args, cb) {
  validate('AF', arguments)
  // the /path/to/node_modules/..
  var where = path.resolve(npm.dir, '..')
  var dryrun = false
  if (npm.command.match(/^find/)) dryrun = true
  if (npm.config.get('dry-run')) dryrun = true
 
  new Deduper(where, dryrun).run(cb)
}
 
function Deduper (where, dryrun) {
  validate('SB', arguments)
  Installer.call(this, where, dryrun, [])
  this.noPackageJsonOk = true
  this.topLevelLifecycles = false
}
util.inherits(Deduper, Installer)
 
Deduper.prototype.loadIdealTree = function (cb) {
  validate('F', arguments)
  log.silly('install', 'loadIdealTree')
 
  var self = this
  chain([
    [this.newTracker(this.progress.loadIdealTree, 'cloneCurrentTree')],
    [this, this.cloneCurrentTreeToIdealTree],
    [this, this.finishTracker, 'cloneCurrentTree'],
 
    [this.newTracker(this.progress.loadIdealTree, 'loadAllDepsIntoIdealTree', 10)],
    [ function (next) {
      loadExtraneous(self.idealTree, self.progress.loadAllDepsIntoIdealTree, next)
    } ],
    [this, this.finishTracker, 'loadAllDepsIntoIdealTree'],
 
    [this, function (next) { recalculateMetadata(this.idealTree, log, next) }]
  ], cb)
}
 
Deduper.prototype.generateActionsToTake = function (cb) {
  validate('F', arguments)
  log.silly('dedupe', 'generateActionsToTake')
  chain([
    [this.newTracker(log, 'hoist', 1)],
    [hoistChildren, this.idealTree, this.differences],
    [this, this.finishTracker, 'hoist'],
    [this.newTracker(log, 'sort-actions', 1)],
    [this, function (next) {
      this.differences = sortActions(this.differences)
      next()
    }],
    [this, this.finishTracker, 'sort-actions'],
    [filterInvalidActions, this.where, this.differences],
    [checkPermissions, this.differences],
    [decomposeActions, this.differences, this.todo]
  ], cb)
}
 
function move (node, hoistTo, diff) {
  node.parent.children = without(node.parent.children, node)
  hoistTo.children.push(node)
  node.fromPath = node.path
  node.path = childPath(hoistTo.path, node)
  node.parent = hoistTo
  if (!diff.filter(function (action) { return action[0] === 'move' && action[1] === node }).length) {
    diff.push(['move', node])
  }
}
 
function moveRemainingChildren (node, diff) {
  node.children.forEach(function (child) {
    move(child, node, diff)
    moveRemainingChildren(child, diff)
  })
}
 
function remove (child, diff, done) {
  remove_(child, diff, {}, done)
}
 
function remove_ (child, diff, seen, done) {
  if (seen[child.path]) return done()
  seen[child.path] = true
  diff.push(['remove', child])
  child.parent.children = without(child.parent.children, child)
  asyncMap(child.children, function (child, next) {
    remove_(child, diff, seen, next)
  }, done)
}
 
function hoistChildren (tree, diff, next) {
  hoistChildren_(tree, diff, {}, next)
}
 
function hoistChildren_ (tree, diff, seen, next) {
  validate('OAOF', arguments)
  if (seen[tree.path]) return next()
  seen[tree.path] = true
  asyncMap(tree.children, function (child, done) {
    if (!tree.parent) return hoistChildren_(child, diff, seen, done)
    var better = findRequirement(tree.parent, moduleName(child), child.package._requested || npa(packageId(child)))
    if (better) {
      return chain([
        [remove, child, diff],
        [recalculateMetadata, tree, log]
      ], done)
    }
    var hoistTo = earliestInstallable(tree, tree.parent, child.package)
    if (hoistTo) {
      move(child, hoistTo, diff)
      chain([
        [recalculateMetadata, hoistTo, log],
        [hoistChildren_, child, diff, seen],
        [ function (next) {
          moveRemainingChildren(child, diff)
          next()
        } ]
      ], done)
    } else {
      done()
    }
  }, next)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/deprecate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/deprecate.js

Statements: 21.21% (7 / 33)      Branches: 0% (0 / 16)      Functions: 0% (0 / 5)      Lines: 26.92% (7 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561 1 1   1   1   1                                             1                                                
var npm = require('./npm.js')
var mapToRegistry = require('./utils/map-to-registry.js')
var npa = require('npm-package-arg')
 
module.exports = deprecate
 
deprecate.usage = 'npm deprecate <pkg>[@<version>] <message>'
 
deprecate.completion = function (opts, cb) {
  // first, get a list of remote packages this user owns.
  // once we have a user account, then don't complete anything.
  if (opts.conf.argv.remain.length > 2) return cb()
  // get the list of packages by user
  var path = '/-/by-user/'
  mapToRegistry(path, npm.config, function (er, uri, c) {
    if (er) return cb(er)
 
    if (!(c && c.username)) return cb()
 
    var params = {
      timeout: 60000,
      auth: c
    }
    npm.registry.get(uri + c.username, params, function (er, list) {
      if (er) return cb()
      console.error(list)
      return cb(null, list[c.username])
    })
  })
}
 
function deprecate (args, cb) {
  var pkg = args[0]
  var msg = args[1]
  if (msg === undefined) return cb('Usage: ' + deprecate.usage)
 
  // fetch the data and make sure it exists.
  var p = npa(pkg)
 
  // npa makes the default spec "latest", but for deprecation
  // "*" is the appropriate default.
  if (p.rawSpec === '') p.spec = '*'
 
  mapToRegistry(p.name, npm.config, function (er, uri, auth) {
    if (er) return cb(er)
 
    var params = {
      version: p.spec,
      message: msg,
      auth: auth
    }
    npm.registry.deprecate(uri, params, cb)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor.js

Statements: 23.75% (19 / 80)      Branches: 0% (0 / 44)      Functions: 0% (0 / 6)      Lines: 27.54% (19 / 69)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 1112 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2               1                                                                                                 1                                                                          
var path = require('path')
var chain = require('slide').chain
var table = require('text-table')
var color = require('ansicolors')
var styles = require('ansistyles')
var semver = require('semver')
var npm = require('./npm.js')
var log = require('npmlog')
var ansiTrim = require('./utils/ansi-trim.js')
var output = require('./utils/output.js')
var defaultRegistry = require('./config/defaults.js').defaults.registry
var checkPing = require('./doctor/check-ping.js')
var getGitPath = require('./doctor/get-git-path.js')
var checksumCachedFiles = require('./doctor/checksum-cached-files.js')
var checkFilesPermission = require('./doctor/check-files-permission.js')
var getLatestNodejsVersion = require('./doctor/get-latest-nodejs-version.js')
var getLatestNpmVersion = require('./doctor/get-latest-npm-version')
var globalNodeModules = path.join(npm.config.globalPrefix, 'lib', 'node_modules')
var localNodeModules = path.join(npm.config.localPrefix, 'node_modules')
 
module.exports = doctor
 
doctor.usage = 'npm doctor'
 
function doctor (args, silent, cb) {
  args = args || {}
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
 
  var actionsToRun = [
    [checkPing],
    [getLatestNpmVersion],
    [getLatestNodejsVersion, args['node-url']],
    [getGitPath],
    [checkFilesPermission, npm.cache, 6],
    [checkFilesPermission, globalNodeModules, 4],
    [checkFilesPermission, localNodeModules, 6],
    [checksumCachedFiles]
  ]
 
  log.info('doctor', 'Running checkup')
  chain(actionsToRun, function (stderr, stdout) {
    if (stderr && stderr.message !== 'not found: git') return cb(stderr)
    var outHead = ['Check', 'Value', 'Recommendation']
    var list = makePretty(stdout)
    var outBody = list
 
    if (npm.color) {
      outHead = outHead.map(function (item) {
        return styles.underline(item)
      })
      outBody = outBody.map(function (item) {
        if (item[2]) {
          item[0] = color.red(item[0])
          item[2] = color.magenta(item[2])
        }
        return item
      })
    }
 
    var outTable = [outHead].concat(outBody)
    var tableOpts = {
      stringLength: function (s) { return ansiTrim(s).length }
    }
 
    if (!silent) output(table(outTable, tableOpts))
 
    cb(null, list)
  })
}
 
function makePretty (p) {
  var ping = p[0] ? 'ok' : 'notOk'
  var npmLTS = p[1]
  var nodeLTS = p[2].replace('v', '')
  var whichGit = p[3] || 'not installed'
  var readbleCaches = p[4] ? 'ok' : 'notOk'
  var executableGlobalModules = p[5] ? 'ok' : 'notOk'
  var executableLocalModules = p[6] ? 'ok' : 'notOk'
  var checksumCachedFiles = p[7] ? 'ok' : 'notOk'
  var npmV = npm.version
  var nodeV = process.version.replace('v', '')
  var registry = npm.config.get('registry')
  var list = [
    ['npm ping', ping],
    ['npm -v', 'v' + npmV],
    ['node -v', 'v' + nodeV],
    ['npm config get registry', registry],
    ['which git', whichGit],
    ['Perms check on cached files', readbleCaches],
    ['Perms check on global node_modules', executableGlobalModules],
    ['Perms check on local node_modules', executableLocalModules],
    ['Checksum cached files', checksumCachedFiles]
  ]
 
  if (ping !== 'ok') list[0][2] = 'Check your internet connection'
  if (!semver.satisfies(npmV, '>=' + npmLTS)) list[1][2] = 'Use npm v' + npmLTS
  if (!semver.satisfies(nodeV, '>=' + nodeLTS)) list[2][2] = 'Use node v' + nodeLTS
  if (registry !== defaultRegistry) list[3][2] = 'Try `npm config set registry ' + defaultRegistry + '`'
  if (whichGit === 'not installed') list[4][2] = 'Install git and ensure it\'s in your PATH.'
  if (readbleCaches !== 'ok') list[5][2] = 'Check the permissions of your files in ' + npm.config.get('cache')
  if (executableGlobalModules !== 'ok') list[6][2] = globalNodeModules + ' must be readable and writable by the current user.'
  if (executableLocalModules !== 'ok') list[7][2] = localNodeModules + ' must be readable and writable by the current user.'
  if (checksumCachedFiles !== 'ok') list[8][2] = 'You have some broken packages in your cache.'
 
  return list
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/edit.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/edit.js

Statements: 37.5% (9 / 24)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 42.86% (9 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37      1 1   1   1 1 1 1 1   1                                            
// npm edit <pkg>
// open the package folder in the $EDITOR
 
module.exports = edit
edit.usage = 'npm edit <pkg>[@<version>]'
 
edit.completion = require('./utils/completion/installed-shallow.js')
 
var npm = require('./npm.js')
var path = require('path')
var fs = require('graceful-fs')
var editor = require('editor')
var noProgressTillDone = require('./utils/no-progress-while-running').tillDone
 
function edit (args, cb) {
  var p = args[0]
  if (args.length !== 1 || !p) return cb(edit.usage)
  var e = npm.config.get('editor')
  if (!e) {
    return cb(new Error(
      "No editor set.  Set the 'editor' config, or $EDITOR environ."
    ))
  }
  p = p.split('/')
       .join('/node_modules/')
       .replace(/(\/node_modules)+/, '/node_modules')
  var f = path.resolve(npm.dir, p)
  fs.lstat(f, function (er) {
    if (er) return cb(er)
    editor(f, { editor: e }, noProgressTillDone(function (er) {
      if (er) return cb(er)
      npm.commands.rebuild(args, cb)
    }))
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/explore.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/explore.js

Statements: 32.43% (12 / 37)      Branches: 0% (0 / 16)      Functions: 0% (0 / 3)      Lines: 34.29% (12 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61      1 1 1   1 1 1 1 1 1 1 1   1                                                                                        
// npm explore <pkg>[@<version>]
// open a subshell to the package folder.
 
module.exports = explore
explore.usage = 'npm explore <pkg> [ -- <cmd>]'
explore.completion = require('./utils/completion/installed-shallow.js')
 
var npm = require('./npm.js')
var spawn = require('./utils/spawn')
var path = require('path')
var fs = require('graceful-fs')
var isWindowsShell = require('./utils/is-windows-shell.js')
var escapeExecPath = require('./utils/escape-exec-path.js')
var escapeArg = require('./utils/escape-arg.js')
var output = require('./utils/output.js')
 
function explore (args, cb) {
  if (args.length < 1 || !args[0]) return cb(explore.usage)
  var p = args.shift()
 
  var cwd = path.resolve(npm.dir, p)
  var opts = {cwd: cwd, stdio: 'inherit'}
 
  var shellArgs = []
  if (args) {
    if (isWindowsShell) {
      var execCmd = escapeExecPath(args.shift())
      var execArgs = [execCmd].concat(args.map(escapeArg))
      opts.windowsVerbatimArguments = true
      shellArgs = ['/d', '/s', '/c'].concat(execArgs)
    } else {
      shellArgs.unshift('-c')
      shellArgs = ['-c', args.map(escapeArg).join(' ').trim()]
    }
  }
 
  var sh = npm.config.get('shell')
  fs.stat(cwd, function (er, s) {
    if (er || !s.isDirectory()) {
      return cb(new Error(
        "It doesn't look like " + p + ' is installed.'
      ))
    }
 
    if (!shellArgs.length) {
      output(
        '\nExploring ' + cwd + '\n' +
          "Type 'exit' or ^D when finished\n"
      )
    }
 
    var shell = spawn(sh, shellArgs, opts)
    shell.on('close', function (er) {
      // only fail if non-interactive.
      if (!shellArgs.length) return cb()
      cb(er)
    })
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/fetch-package-metadata.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/fetch-package-metadata.js

Statements: 14% (35 / 250)      Branches: 0% (0 / 99)      Functions: 0% (0 / 41)      Lines: 15.22% (35 / 230)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/ » fetch-package-metadata.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356  26 26 26   26 26 26 26 26 26 26 26 26 26 26 26 26 26   26 26 26                 1                         1                                                   1                                               1                   1               1                   1             1                                                                                   1                                                                                                                                                                                                     1       1                               1                                                         1                       1                       1                        
'use strict'
var fs = require('graceful-fs')
var path = require('path')
var zlib = require('zlib')
 
var log = require('npmlog')
var realizePackageSpecifier = require('realize-package-specifier')
var tar = require('tar')
var once = require('once')
var semver = require('semver')
var readPackageTree = require('read-package-tree')
var readPackageJson = require('read-package-json')
var iferr = require('iferr')
var rimraf = require('rimraf')
var clone = require('lodash.clonedeep')
var validate = require('aproba')
var unpipe = require('unpipe')
var normalizePackageData = require('normalize-package-data')
var limit = require('call-limit')
 
var npm = require('./npm.js')
var mapToRegistry = require('./utils/map-to-registry.js')
var cache = require('./cache.js')
var cachedPackageRoot = require('./cache/cached-package-root.js')
var tempFilename = require('./utils/temp-filename.js')
var getCacheStat = require('./cache/get-stat.js')
var unpack = require('./utils/tar.js').unpack
var pulseTillDone = require('./utils/pulse-till-done.js')
var parseJSON = require('./utils/parse-json.js')
var pickManifestFromRegistryMetadata = require('./utils/pick-manifest-from-registry-metadata.js')
 
function andLogAndFinish (spec, tracker, done) {
  validate('SF', [spec, done])
  return function (er, pkg) {
    if (er) {
      log.silly('fetchPackageMetaData', 'error for ' + spec, er)
      if (tracker) tracker.finish()
    }
    return done(er, pkg)
  }
}
 
module.exports = limit(fetchPackageMetadata, npm.limit.fetch)
 
function fetchPackageMetadata (spec, where, opts, done) {
  validate('SSOF|SSFZ|OSOF|OSFZ', [spec, where, opts, done])
 
  if (!done) {
    done = opts
    opts = {}
  }
  var tracker = opts.tracker
  if (typeof spec === 'object') {
    var dep = spec
    spec = dep.raw
  }
  var logAndFinish = andLogAndFinish(spec, tracker, done)
  if (!dep) {
    log.silly('fetchPackageMetaData', spec)
    return realizePackageSpecifier(spec, where, iferr(logAndFinish, function (dep) {
      fetchPackageMetadata(dep, where, {tracker: tracker}, done)
    }))
  }
  if (dep.type === 'version' || dep.type === 'range' || dep.type === 'tag') {
    fetchNamedPackageData(dep, opts, addRequestedAndFinish)
  } else if (dep.type === 'directory') {
    fetchDirectoryPackageData(dep, where, addRequestedAndFinish)
  } else {
    fetchOtherPackageData(spec, dep, where, addRequestedAndFinish)
  }
  function addRequestedAndFinish (er, pkg) {
    if (pkg) annotateMetadata(pkg, dep, spec, where)
    logAndFinish(er, pkg)
  }
}
 
var annotateMetadata = module.exports.annotateMetadata = function (pkg, requested, spec, where) {
  validate('OOSS', arguments)
  pkg._requested = requested
  pkg._spec = spec
  pkg._where = where
  if (!pkg._args) pkg._args = []
  pkg._args.push([requested, where])
  // non-npm registries can and will return unnormalized data, plus
  // even the npm registry may have package data normalized with older
  // normalization rules. This ensures we get package data in a consistent,
  // stable format.
  try {
    normalizePackageData(pkg)
  } catch (ex) {
    // don't care
  }
}
 
function fetchOtherPackageData (spec, dep, where, next) {
  validate('SOSF', arguments)
  log.silly('fetchOtherPackageData', spec)
  cache.add(spec, null, where, false, iferr(next, function (pkg) {
    var result = clone(pkg)
    result._inCache = true
    next(null, result)
  }))
}
 
function fetchDirectoryPackageData (dep, where, next) {
  validate('OSF', arguments)
  log.silly('fetchDirectoryPackageData', dep.name || dep.rawSpec)
  readPackageJson(path.join(dep.spec, 'package.json'), false, next)
}
 
var regCache = {}
 
function fetchNamedPackageData (dep, opts, next) {
  validate('OOF', arguments)
  log.silly('fetchNamedPackageData', dep.name || dep.rawSpec)
  mapToRegistry(dep.name || dep.rawSpec, npm.config, iferr(next, function (url, auth) {
    if (regCache[url]) {
      pickVersionFromRegistryDocument(clone(regCache[url]))
    } else {
      var fullMetadata = opts.fullMetadata == null ? true : opts.fullMetadata
      npm.registry.get(url, {auth: auth, fullMetadata: fullMetadata}, pulseTillDone('fetchMetadata', iferr(next, pickVersionFromRegistryDocument)))
    }
    function thenAddMetadata (pkg) {
      pkg._from = dep.raw
      pkg._resolved = pkg.dist.tarball
      pkg._shasum = pkg.dist.shasum
 
      next(null, pkg)
    }
    function pickVersionFromRegistryDocument (pkg) {
      if (!regCache[url]) regCache[url] = pkg
      var versions = Object.keys(pkg.versions)
 
      var invalidVersions = versions.filter(function (v) { return !semver.valid(v) })
      if (invalidVersions.length > 0) {
        log.warn('pickVersion', 'The package %s has invalid semver-version(s): %s. This usually only happens for unofficial private registries. ' +
            'You should delete or re-publish the invalid versions.', pkg.name, invalidVersions.join(', '))
      }
 
      versions = versions.filter(function (v) { return semver.valid(v) })
 
      if (dep.type === 'tag') {
        var tagVersion = pkg['dist-tags'][dep.spec]
        if (pkg.versions[tagVersion]) return thenAddMetadata(pkg.versions[tagVersion])
      } else {
        var picked = pickManifestFromRegistryMetadata(dep.spec, npm.config.get('tag'), versions, pkg)
        if (picked) return thenAddMetadata(picked.manifest)
      }
 
      // We didn't manage to find a compatible version
      // If this package was requested from cache, force hitting the network
      if (pkg._cached) {
        log.silly('fetchNamedPackageData', 'No valid target from cache, forcing network')
        return npm.registry.get(url, {
          auth: auth,
          skipCache: true
        }, pulseTillDone('fetchMetadata', iferr(next, pickVersionFromRegistryDocument)))
      }
 
      // And failing that, we error out
      var targets = versions.length
                  ? 'Valid install targets:\n' + versions.join(', ') + '\n'
                  : 'No valid targets found.'
      var er = new Error('No compatible version found: ' +
                         dep.raw + '\n' + targets)
      er.code = 'ETARGET'
      return next(er)
    }
  }))
}
 
function retryWithCached (pkg, asserter, next) {
  if (!pkg._inCache) {
    cache.add(pkg._spec, null, pkg._where, false, iferr(next, function (newpkg) {
      Object.keys(newpkg).forEach(function (key) {
        if (key[0] !== '_') return
        pkg[key] = newpkg[key]
      })
      pkg._inCache = true
      return asserter(pkg, next)
    }))
  }
  return !pkg._inCache
}
 
module.exports.addShrinkwrap = function addShrinkwrap (pkg, next) {
  validate('OF', arguments)
  if (pkg._shrinkwrap !== undefined) return next(null, pkg)
  if (pkg._hasShrinkwrap === false) {
    pkg._shrinkwrap = null
    return next(null, pkg)
  }
  if (retryWithCached(pkg, addShrinkwrap, next)) return
  pkg._shrinkwrap = null
  // FIXME: cache the shrinkwrap directly
  var pkgname = pkg.name
  var ver = pkg.version
  var tarball = path.join(cachedPackageRoot({name: pkgname, version: ver}), 'package.tgz')
  untarStream(tarball, function (er, untar) {
    if (er) {
      if (er.code === 'ENOTTARBALL') {
        pkg._shrinkwrap = null
        return next()
      } else {
        return next(er)
      }
    }
    if (er) return next(er)
    var foundShrinkwrap = false
    untar.on('entry', function (entry) {
      if (!/^(?:[^\/]+[\/])npm-shrinkwrap.json$/.test(entry.path)) return
      log.silly('addShrinkwrap', 'Found shrinkwrap in ' + pkgname + ' ' + entry.path)
      foundShrinkwrap = true
      var shrinkwrap = ''
      entry.on('data', function (chunk) {
        shrinkwrap += chunk
      })
      entry.on('end', function () {
        untar.close()
        log.silly('addShrinkwrap', 'Completed reading shrinkwrap in ' + pkgname)
        try {
          pkg._shrinkwrap = parseJSON(shrinkwrap)
        } catch (ex) {
          var er = new Error('Error parsing ' + pkgname + '@' + ver + "'s npm-shrinkwrap.json: " + ex.message)
          er.type = 'ESHRINKWRAP'
          return next(er)
        }
        next(null, pkg)
      })
      entry.resume()
    })
    untar.on('end', function () {
      if (!foundShrinkwrap) {
        pkg._shrinkwrap = null
        next(null, pkg)
      }
    })
  })
}
 
module.exports.addBundled = function addBundled (pkg, next) {
  validate('OF', arguments)
  if (pkg._bundled !== undefined) return next(null, pkg)
  if (!pkg.bundleDependencies) return next(null, pkg)
  if (retryWithCached(pkg, addBundled, next)) return
  pkg._bundled = null
  var pkgname = pkg.name
  var ver = pkg.version
  var tarball = path.join(cachedPackageRoot({name: pkgname, version: ver}), 'package.tgz')
  var target = tempFilename('unpack')
  getCacheStat(iferr(next, function (cs) {
    log.verbose('addBundled', 'extract', tarball)
    unpack(tarball, target, null, null, cs.uid, cs.gid, iferr(next, function () {
      log.silly('addBundled', 'read tarball')
      readPackageTree(target, function (er, tree) {
        log.silly('cleanup', 'remove extracted module')
        rimraf(target, function () {
          if (tree) {
            pkg._bundled = tree.children
          }
          next(null, pkg)
        })
      })
    }))
  }))
}
 
// FIXME: hasGzipHeader / hasTarHeader / untarStream duplicate a lot
// of code from lib/utils/tar.js– these should be brought together.
 
function hasGzipHeader (c) {
  return c[0] === 0x1F && c[1] === 0x8B && c[2] === 0x08
}
 
function hasTarHeader (c) {
  return c[257] === 0x75 && // tar archives have 7573746172 at position
         c[258] === 0x73 && // 257 and 003030 or 202000 at position 262
         c[259] === 0x74 &&
         c[260] === 0x61 &&
         c[261] === 0x72 &&
 
       ((c[262] === 0x00 &&
         c[263] === 0x30 &&
         c[264] === 0x30) ||
 
        (c[262] === 0x20 &&
         c[263] === 0x20 &&
         c[264] === 0x00))
}
 
function untarStream (tarball, cb) {
  validate('SF', arguments)
  cb = once(cb)
 
  var stream
  var file = stream = fs.createReadStream(tarball)
  var tounpipe = [file]
  file.on('error', function (er) {
    er = new Error('Error extracting ' + tarball + ' archive: ' + er.message)
    er.code = 'EREADFILE'
    cb(er)
  })
  file.on('data', function OD (c) {
    if (hasGzipHeader(c)) {
      doGunzip()
    } else if (hasTarHeader(c)) {
      doUntar()
    } else {
      if (file.close) file.close()
      if (file.destroy) file.destroy()
      var er = new Error('Non-gzip/tarball ' + tarball)
      er.code = 'ENOTTARBALL'
      return cb(er)
    }
    file.removeListener('data', OD)
    file.emit('data', c)
    cb(null, stream)
  })
 
  function doGunzip () {
    var gunzip = stream.pipe(zlib.createGunzip())
    gunzip.on('error', function (er) {
      er = new Error('Error extracting ' + tarball + ' archive: ' + er.message)
      er.code = 'EGUNZIP'
      cb(er)
    })
    tounpipe.push(gunzip)
    stream = gunzip
    doUntar()
  }
 
  function doUntar () {
    var untar = stream.pipe(tar.Parse())
    untar.on('error', function (er) {
      er = new Error('Error extracting ' + tarball + ' archive: ' + er.message)
      er.code = 'EUNTAR'
      cb(er)
    })
    tounpipe.push(untar)
    stream = untar
    addClose()
  }
 
  function addClose () {
    stream.close = function () {
      tounpipe.forEach(function (stream) {
        unpipe(stream)
      })
 
      if (file.close) file.close()
      if (file.destroy) file.destroy()
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/get.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/get.js

Statements: 83.33% (5 / 6)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 83.33% (5 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14  2   2   2   2   1        
 
module.exports = get
 
get.usage = 'npm get <key> <value> (See `npm config`)'
 
var npm = require('./npm.js')
 
get.completion = npm.commands.config.completion
 
function get (args, cb) {
  npm.commands.config(['get'].concat(args), cb)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/help-search.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/help-search.js

Statements: 10.57% (13 / 123)      Branches: 0% (0 / 74)      Functions: 0% (0 / 20)      Lines: 11.71% (13 / 111)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214  1   1 1 1 1 1 1 1   1   1                                       1                       1                                                                                                                                                                                                                               1                                                                                                                
 
module.exports = helpSearch
 
var fs = require('graceful-fs')
var path = require('path')
var asyncMap = require('slide').asyncMap
var npm = require('./npm.js')
var glob = require('glob')
var color = require('ansicolors')
var output = require('./utils/output.js')
 
helpSearch.usage = 'npm help-search <text>'
 
function helpSearch (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
  if (!args.length) return cb(helpSearch.usage)
 
  var docPath = path.resolve(__dirname, '..', 'doc')
  return glob(docPath + '/*/*.md', function (er, files) {
    if (er) return cb(er)
    readFiles(files, function (er, data) {
      if (er) return cb(er)
      searchFiles(args, data, function (er, results) {
        if (er) return cb(er)
        formatResults(args, results, cb)
      })
    })
  })
}
 
function readFiles (files, cb) {
  var res = {}
  asyncMap(files, function (file, cb) {
    fs.readFile(file, 'utf8', function (er, data) {
      res[file] = data
      return cb(er)
    })
  }, function (er) {
    return cb(er, res)
  })
}
 
function searchFiles (args, files, cb) {
  var results = []
  Object.keys(files).forEach(function (file) {
    var data = files[file]
 
    // skip if no matches at all
    var match
    for (var a = 0, l = args.length; a < l && !match; a++) {
      match = data.toLowerCase().indexOf(args[a].toLowerCase()) !== -1
    }
    if (!match) return
 
    var lines = data.split(/\n+/)
 
    // if a line has a search term, then skip it and the next line.
    // if the next line has a search term, then skip all 3
    // otherwise, set the line to null.  then remove the nulls.
    l = lines.length
    for (var i = 0; i < l; i++) {
      var line = lines[i]
      var nextLine = lines[i + 1]
      var ll
 
      match = false
      if (nextLine) {
        for (a = 0, ll = args.length; a < ll && !match; a++) {
          match = nextLine.toLowerCase()
                  .indexOf(args[a].toLowerCase()) !== -1
        }
        if (match) {
          // skip over the next line, and the line after it.
          i += 2
          continue
        }
      }
 
      match = false
      for (a = 0, ll = args.length; a < ll && !match; a++) {
        match = line.toLowerCase().indexOf(args[a].toLowerCase()) !== -1
      }
      if (match) {
        // skip over the next line
        i++
        continue
      }
 
      lines[i] = null
    }
 
    // now squish any string of nulls into a single null
    lines = lines.reduce(function (l, r) {
      if (!(r === null && l[l.length - 1] === null)) l.push(r)
      return l
    }, [])
 
    if (lines[lines.length - 1] === null) lines.pop()
    if (lines[0] === null) lines.shift()
 
    // now see how many args were found at all.
    var found = {}
    var totalHits = 0
    lines.forEach(function (line) {
      args.forEach(function (arg) {
        var hit = (line || '').toLowerCase()
                  .split(arg.toLowerCase()).length - 1
        if (hit > 0) {
          found[arg] = (found[arg] || 0) + hit
          totalHits += hit
        }
      })
    })
 
    var cmd = 'npm help '
    if (path.basename(path.dirname(file)) === 'api') {
      cmd = 'npm apihelp '
    }
    cmd += path.basename(file, '.md').replace(/^npm-/, '')
    results.push({
      file: file,
      cmd: cmd,
      lines: lines,
      found: Object.keys(found),
      hits: found,
      totalHits: totalHits
    })
  })
 
  // if only one result, then just show that help section.
  if (results.length === 1) {
    return npm.commands.help([results[0].file.replace(/\.md$/, '')], cb)
  }
 
  if (results.length === 0) {
    output('No results for ' + args.map(JSON.stringify).join(' '))
    return cb()
  }
 
  // sort results by number of results found, then by number of hits
  // then by number of matching lines
  results = results.sort(function (a, b) {
    return a.found.length > b.found.length ? -1
         : a.found.length < b.found.length ? 1
         : a.totalHits > b.totalHits ? -1
         : a.totalHits < b.totalHits ? 1
         : a.lines.length > b.lines.length ? -1
         : a.lines.length < b.lines.length ? 1
         : 0
  })
 
  cb(null, results)
}
 
function formatResults (args, results, cb) {
  if (!results) return cb(null)
 
  var cols = Math.min(process.stdout.columns || Infinity, 80) + 1
 
  var out = results.map(function (res) {
    var out = res.cmd
    var r = Object.keys(res.hits)
      .map(function (k) {
        return k + ':' + res.hits[k]
      }).sort(function (a, b) {
        return a > b ? 1 : -1
      }).join(' ')
 
    out += ((new Array(Math.max(1, cols - out.length - r.length)))
             .join(' ')) + r
 
    if (!npm.config.get('long')) return out
 
    out = '\n\n' + out + '\n' +
      (new Array(cols)).join('—') + '\n' +
      res.lines.map(function (line, i) {
        if (line === null || i > 3) return ''
        for (var out = line, a = 0, l = args.length; a < l; a++) {
          var finder = out.toLowerCase().split(args[a].toLowerCase())
          var newOut = ''
          var p = 0
 
          finder.forEach(function (f) {
            newOut += out.substr(p, f.length)
 
            var hilit = out.substr(p + f.length, args[a].length)
            if (npm.color) hilit = color.bgBlack(color.red(hilit))
            newOut += hilit
 
            p += f.length + args[a].length
          })
        }
 
        return newOut
      }).join('\n').trim()
    return out
  }).join('\n')
 
  if (results.length && !npm.config.get('long')) {
    out = 'Top hits for ' + (args.map(JSON.stringify).join(' ')) + '\n' +
          (new Array(cols)).join('—') + '\n' +
          out + '\n' +
          (new Array(cols)).join('—') + '\n' +
          '(run with -l or --long to see more context)'
  }
 
  output(out.trim())
  cb(null, results)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/help.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/help.js

Statements: 14.08% (20 / 142)      Branches: 0% (0 / 63)      Functions: 0% (0 / 22)      Lines: 14.93% (20 / 134)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243  1   1         1 1 1 1 1 1 1 1 1 1   1                                                                                                                                         1                               1                                                                     1                                           1                                                 1                                   1                                               1                            
 
module.exports = help
 
help.completion = function (opts, cb) {
  if (opts.conf.argv.remain.length > 2) return cb(null, [])
  getSections(cb)
}
 
var path = require('path')
var spawn = require('./utils/spawn')
var npm = require('./npm.js')
var log = require('npmlog')
var opener = require('opener')
var glob = require('glob')
var cmdList = require('./config/cmd-list').cmdList
var shorthands = require('./config/cmd-list').shorthands
var commands = cmdList.concat(Object.keys(shorthands))
var output = require('./utils/output.js')
 
function help (args, cb) {
  var argv = npm.config.get('argv').cooked
 
  var argnum = 0
  if (args.length === 2 && ~~args[0]) {
    argnum = ~~args.shift()
  }
 
  // npm help foo bar baz: search topics
  if (args.length > 1 && args[0]) {
    return npm.commands['help-search'](args, argnum, cb)
  }
 
  var section = npm.deref(args[0]) || args[0]
 
  // npm help <noargs>:  show basic usage
  if (!section) {
    var valid = argv[0] === 'help' ? 0 : 1
    return npmUsage(valid, cb)
  }
 
  // npm <cmd> -h: show command usage
  if (npm.config.get('usage') &&
      npm.commands[section] &&
      npm.commands[section].usage) {
    npm.config.set('loglevel', 'silent')
    log.level = 'silent'
    output(npm.commands[section].usage)
    return cb()
  }
 
  // npm apihelp <section>: Prefer section 3 over section 1
  var apihelp = argv.length && argv[0].indexOf('api') !== -1
  var pref = apihelp ? [3, 1, 5, 7] : [1, 3, 5, 7]
  if (argnum) {
    pref = [ argnum ].concat(pref.filter(function (n) {
      return n !== argnum
    }))
  }
 
  // npm help <section>: Try to find the path
  var manroot = path.resolve(__dirname, '..', 'man')
 
  // legacy
  if (section === 'global') section = 'folders'
  else if (section === 'json') section = 'package.json'
 
  // find either /section.n or /npm-section.n
  // The glob is used in the glob.  The regexp is used much
  // further down.  Globs and regexps are different
  var compextglob = '.+(gz|bz2|lzma|[FYzZ]|xz)'
  var compextre = '\\.(gz|bz2|lzma|[FYzZ]|xz)$'
  var f = '+(npm-' + section + '|' + section + ').[0-9]?(' + compextglob + ')'
  return glob(manroot + '/*/' + f, function (er, mans) {
    if (er) return cb(er)
 
    if (!mans.length) return npm.commands['help-search'](args, cb)
 
    mans = mans.map(function (man) {
      var ext = path.extname(man)
      if (man.match(new RegExp(compextre))) man = path.basename(man, ext)
 
      return man
    })
 
    viewMan(pickMan(mans, pref), cb)
  })
}
 
function pickMan (mans, pref_) {
  var nre = /([0-9]+)$/
  var pref = {}
  pref_.forEach(function (sect, i) {
    pref[sect] = i
  })
  mans = mans.sort(function (a, b) {
    var an = a.match(nre)[1]
    var bn = b.match(nre)[1]
    return an === bn ? (a > b ? -1 : 1)
         : pref[an] < pref[bn] ? -1
         : 1
  })
  return mans[0]
}
 
function viewMan (man, cb) {
  var nre = /([0-9]+)$/
  var num = man.match(nre)[1]
  var section = path.basename(man, '.' + num)
 
  // at this point, we know that the specified man page exists
  var manpath = path.join(__dirname, '..', 'man')
  var env = {}
  Object.keys(process.env).forEach(function (i) {
    env[i] = process.env[i]
  })
  env.MANPATH = manpath
  var viewer = npm.config.get('viewer')
 
  var conf
  switch (viewer) {
    case 'woman':
      var a = ['-e', '(woman-find-file \'' + man + '\')']
      conf = { env: env, stdio: 'inherit' }
      var woman = spawn('emacsclient', a, conf)
      woman.on('close', cb)
      break
 
    case 'browser':
      opener(htmlMan(man), { command: npm.config.get('browser') }, cb)
      break
 
    default:
      conf = { env: env, stdio: 'inherit' }
      var manProcess = spawn('man', [num, section], conf)
      manProcess.on('close', cb)
      break
  }
}
 
function htmlMan (man) {
  var sect = +man.match(/([0-9]+)$/)[1]
  var f = path.basename(man).replace(/([0-9]+)$/, 'html')
  switch (sect) {
    case 1:
      sect = 'cli'
      break
    case 3:
      sect = 'api'
      break
    case 5:
      sect = 'files'
      break
    case 7:
      sect = 'misc'
      break
    default:
      throw new Error('invalid man section: ' + sect)
  }
  return path.resolve(__dirname, '..', 'html', 'doc', sect, f)
}
 
function npmUsage (valid, cb) {
  npm.config.set('loglevel', 'silent')
  log.level = 'silent'
  output([
    '\nUsage: npm <command>',
    '',
    'where <command> is one of:',
    npm.config.get('long') ? usages()
        : '    ' + wrap(commands),
    '',
    'npm <cmd> -h     quick help on <cmd>',
    'npm -l           display full usage info',
    'npm help <term>  search for help on <term>',
    'npm help npm     involved overview',
    '',
    'Specify configs in the ini-formatted file:',
    '    ' + npm.config.get('userconfig'),
    'or on the command line via: npm <command> --key value',
    'Config info can be viewed via: npm help config',
    '',
    'npm@' + npm.version + ' ' + path.dirname(__dirname)
  ].join('\n'))
  cb(valid)
}
 
function usages () {
  // return a string of <cmd>: <usage>
  var maxLen = 0
  return Object.keys(npm.commands).filter(function (c) {
    return c === npm.deref(c)
  }).reduce(function (set, c) {
    set.push([c, npm.commands[c].usage || ''])
    maxLen = Math.max(maxLen, c.length)
    return set
  }, []).map(function (item) {
    var c = item[0]
    var usage = item[1]
    return '\n    ' +
      c + (new Array(maxLen - c.length + 2).join(' ')) +
      (usage.split('\n').join('\n' + (new Array(maxLen + 6).join(' '))))
  }).join('\n')
}
 
function wrap (arr) {
  var out = ['']
  var l = 0
  var line
 
  line = process.stdout.columns
  if (!line) {
    line = 60
  } else {
    line = Math.min(60, Math.max(line - 16, 24))
  }
 
  arr.sort(function (a, b) { return a < b ? -1 : 1 })
    .forEach(function (c) {
      if (out[l].length + c.length + 2 < line) {
        out[l] += ', ' + c
      } else {
        out[l++] += ','
        out[l] = c
      }
    })
  return out.join('\n    ').substr(2)
}
 
function getSections (cb) {
  var g = path.resolve(__dirname, '../man/man[0-9]/*.[0-9]')
  glob(g, function (er, files) {
    if (er) return cb(er)
 
    cb(null, Object.keys(files.reduce(function (acc, file) {
      file = path.basename(file).replace(/\.[0-9]+$/, '')
      file = file.replace(/^npm-/, '')
      acc[file] = true
      return acc
    }, { help: true })))
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/init.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/init.js

Statements: 38.1% (8 / 21)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 38.1% (8 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43    1   1 1 1 1 1   1   1                                                            
// initialize a package.json file
 
module.exports = init
 
var log = require('npmlog')
var npm = require('./npm.js')
var initJson = require('init-package-json')
var output = require('./utils/output.js')
var noProgressTillDone = require('./utils/no-progress-while-running').tillDone
 
init.usage = 'npm init [--force|-f|--yes|-y]'
 
function init (args, cb) {
  var dir = process.cwd()
  log.pause()
  var initFile = npm.config.get('init-module')
  if (!initJson.yes(npm.config)) {
    output([
      'This utility will walk you through creating a package.json file.',
      'It only covers the most common items, and tries to guess sensible defaults.',
      '',
      'See `npm help json` for definitive documentation on these fields',
      'and exactly what they do.',
      '',
      'Use `npm install <pkg> --save` afterwards to install a package and',
      'save it as a dependency in the package.json file.',
      '',
      'Press ^C at any time to quit.'
    ].join('\n'))
  }
  initJson(dir, initFile, npm.config, noProgressTillDone(function (er, data) {
    log.resume()
    log.silly('package data', data)
    if (er && er.message === 'canceled') {
      log.warn('init', 'canceled')
      return cb(null, data)
    }
    log.info('init', 'written successfully')
    cb(er, data)
  }))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install.js

Statements: 6.25% (28 / 448)      Branches: 0% (0 / 158)      Functions: 0% (0 / 89)      Lines: 6.75% (28 / 415)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739                            12 12   12   12                             12                                                                                                                       12 12     12 12 12 12 12 12 12 12 12     12 12 12 12 12                                                               1                     1                         1                                                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1     1                    
'use strict'
// npm install <pkg> <pkg> <pkg>
//
// See doc/cli/npm-install.md for more description
//
// Managing contexts...
// there's a lot of state associated with an "install" operation, including
// packages that are already installed, parent packages, current shrinkwrap, and
// so on. We maintain this state in a "context" object that gets passed around.
// every time we dive into a deeper node_modules folder, the "family" list that
// gets passed along uses the previous "family" list as its __proto__.  Any
// "resolved precise dependency" things that aren't already on this object get
// added, and then that's passed to the next generation of installation.
 
module.exports = install
module.exports.Installer = Installer
 
var usage = require('./utils/usage')
 
install.usage = usage(
  'install',
  '\nnpm install (with no args, in package dir)' +
  '\nnpm install [<@scope>/]<pkg>' +
  '\nnpm install [<@scope>/]<pkg>@<tag>' +
  '\nnpm install [<@scope>/]<pkg>@<version>' +
  '\nnpm install [<@scope>/]<pkg>@<version range>' +
  '\nnpm install <folder>' +
  '\nnpm install <tarball file>' +
  '\nnpm install <tarball url>' +
  '\nnpm install <git:// url>' +
  '\nnpm install <github username>/<github project>',
  '[--save|--save-dev|--save-optional] [--save-exact]'
)
 
install.completion = function (opts, cb) {
  validate('OF', arguments)
  // install can complete to a folder with a package.json, or any package.
  // if it has a slash, then it's gotta be a folder
  // if it starts with https?://, then just give up, because it's a url
  if (/^https?:\/\//.test(opts.partialWord)) {
    // do not complete to URLs
    return cb(null, [])
  }
 
  if (/\//.test(opts.partialWord)) {
    // Complete fully to folder if there is exactly one match and it
    // is a folder containing a package.json file.  If that is not the
    // case we return 0 matches, which will trigger the default bash
    // complete.
    var lastSlashIdx = opts.partialWord.lastIndexOf('/')
    var partialName = opts.partialWord.slice(lastSlashIdx + 1)
    var partialPath = opts.partialWord.slice(0, lastSlashIdx)
    if (partialPath === '') partialPath = '/'
 
    var annotatePackageDirMatch = function (sibling, cb) {
      var fullPath = path.join(partialPath, sibling)
      if (sibling.slice(0, partialName.length) !== partialName) {
        return cb(null, null) // not name match
      }
      fs.readdir(fullPath, function (err, contents) {
        if (err) return cb(null, { isPackage: false })
 
        cb(
          null,
          {
            fullPath: fullPath,
            isPackage: contents.indexOf('package.json') !== -1
          }
        )
      })
    }
 
    return fs.readdir(partialPath, function (err, siblings) {
      if (err) return cb(null, []) // invalid dir: no matching
 
      asyncMap(siblings, annotatePackageDirMatch, function (err, matches) {
        if (err) return cb(err)
 
        var cleaned = matches.filter(function (x) { return x !== null })
        if (cleaned.length !== 1) return cb(null, [])
        if (!cleaned[0].isPackage) return cb(null, [])
 
        // Success - only one match and it is a package dir
        return cb(null, [cleaned[0].fullPath])
      })
    })
  }
 
  // FIXME: there used to be registry completion here, but it stopped making
  // sense somewhere around 50,000 packages on the registry
  cb()
}
 
// system packages
var fs = require('fs')
var path = require('path')
 
// dependencies
var log = require('npmlog')
var readPackageTree = require('read-package-tree')
var chain = require('slide').chain
var asyncMap = require('slide').asyncMap
var archy = require('archy')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var iferr = require('iferr')
var validate = require('aproba')
 
// npm internal utils
var npm = require('./npm.js')
var locker = require('./utils/locker.js')
var lock = locker.lock
var unlock = locker.unlock
var ls = require('./ls.js')
var parseJSON = require('./utils/parse-json.js')
var output = require('./utils/output.js')
var saveMetrics = require('./utils/metrics.js').save
 
// install specific libraries
var copyTree = require('./install/copy-tree.js')
var readShrinkwrap = require('./install/read-shrinkwrap.js')
var recalculateMetadata = require('./install/deps.js').recalculateMetadata
var loadDeps = require('./install/deps.js').loadDeps
var loadDevDeps = require('./install/deps.js').loadDevDeps
var getAllMetadata = require('./install/deps.js').getAllMetadata
var loadRequestedDeps = require('./install/deps.js').loadRequestedDeps
var loadExtraneous = require('./install/deps.js').loadExtraneous
var diffTrees = require('./install/diff-trees.js')
var checkPermissions = require('./install/check-permissions.js')
var decomposeActions = require('./install/decompose-actions.js')
var filterInvalidActions = require('./install/filter-invalid-actions.js')
var validateTree = require('./install/validate-tree.js')
var validateArgs = require('./install/validate-args.js')
var saveRequested = require('./install/save.js').saveRequested
var getSaveType = require('./install/save.js').getSaveType
var doSerialActions = require('./install/actions.js').doSerial
var doReverseSerialActions = require('./install/actions.js').doReverseSerial
var doParallelActions = require('./install/actions.js').doParallel
var doOneAction = require('./install/actions.js').doOne
var removeObsoleteDep = require('./install/deps.js').removeObsoleteDep
var packageId = require('./utils/package-id.js')
var moduleName = require('./utils/module-name.js')
var errorMessage = require('./utils/error-message.js')
var andIgnoreErrors = require('./install/and-ignore-errors.js')
 
function unlockCB (lockPath, name, cb) {
  validate('SSF', arguments)
  return function (installEr) {
    var args = arguments
    try {
      unlock(lockPath, name, reportErrorAndReturn)
    } catch (unlockEx) {
      process.nextTick(function () {
        reportErrorAndReturn(unlockEx)
      })
    }
    function reportErrorAndReturn (unlockEr) {
      if (installEr) {
        if (unlockEr && unlockEr.code !== 'ENOTLOCKED') {
          log.warn('unlock' + name, unlockEr)
        }
        return cb.apply(null, args)
      }
      if (unlockEr) return cb(unlockEr)
      return cb.apply(null, args)
    }
  }
}
 
function install (where, args, cb) {
  if (!cb) {
    cb = args
    args = where
    where = null
  }
  var globalTop = path.resolve(npm.globalDir, '..')
  if (!where) {
    where = npm.config.get('global')
          ? globalTop
          : npm.prefix
  }
  validate('SAF', [where, args, cb])
  // the /path/to/node_modules/..
  var dryrun = !!npm.config.get('dry-run')
 
  if (npm.config.get('dev')) {
    log.warn('install', 'Usage of the `--dev` option is deprecated. Use `--only=dev` instead.')
  }
 
  if (where === globalTop && !args.length) {
    args = ['.']
  }
  args = args.filter(function (a) {
    return path.resolve(a) !== npm.prefix
  })
 
  new Installer(where, dryrun, args).run(cb)
}
 
function Installer (where, dryrun, args) {
  validate('SBA', arguments)
  this.where = where
  this.dryrun = dryrun
  this.args = args
  this.currentTree = null
  this.idealTree = null
  this.differences = []
  this.todo = []
  this.progress = {}
  this.noPackageJsonOk = !!args.length
  this.topLevelLifecycles = !args.length
  this.dev = npm.config.get('dev') || (!/^prod(uction)?$/.test(npm.config.get('only')) && !npm.config.get('production')) || /^dev(elopment)?$/.test(npm.config.get('only'))
  this.prod = !/^dev(elopment)?$/.test(npm.config.get('only'))
  this.rollback = npm.config.get('rollback')
  this.link = npm.config.get('link')
  this.global = this.where === path.resolve(npm.globalDir, '..')
}
Installer.prototype = {}
 
Installer.prototype.run = function (_cb) {
  validate('F', arguments)
 
  var cb = function (err) {
    saveMetrics(!err)
    return _cb.apply(this, arguments)
  }
 
  // FIXME: This is bad and I should feel bad.
  // lib/install needs to have some way of sharing _limited_
  // state with the things it calls. Passing the object is too
  // much. The global config is WAY too much. =( =(
  // But not having this is gonna break linked modules in
  // subtle stupid ways, and refactoring all this code isn't
  // the right thing to do just yet.
  if (this.global) {
    var prevGlobal = npm.config.get('global')
    npm.config.set('global', true)
    var next = cb
    cb = function () {
      npm.config.set('global', prevGlobal)
      next.apply(null, arguments)
    }
  }
 
  var installSteps = []
  var postInstallSteps = []
  installSteps.push(
    [this.newTracker(log, 'loadCurrentTree', 4)],
    [this, this.loadCurrentTree],
    [this, this.finishTracker, 'loadCurrentTree'],
 
    [this.newTracker(log, 'loadIdealTree', 12)],
    [this, this.loadIdealTree],
    [this, this.finishTracker, 'loadIdealTree'],
 
    [this, this.debugTree, 'currentTree', 'currentTree'],
    [this, this.debugTree, 'idealTree', 'idealTree'],
 
    [this.newTracker(log, 'generateActionsToTake')],
    [this, this.generateActionsToTake],
    [this, this.finishTracker, 'generateActionsToTake'],
 
    [this, this.debugActions, 'diffTrees', 'differences'],
    [this, this.debugActions, 'decomposeActions', 'todo'])
  if (!this.dryrun) {
    installSteps.push(
      [this.newTracker(log, 'runTopLevelLifecycles', 2)],
      [this, this.runPreinstallTopLevelLifecycles],
 
      [this.newTracker(log, 'executeActions', 8)],
      [this, this.executeActions],
      [this, this.finishTracker, 'executeActions'])
    var node_modules = path.resolve(this.where, 'node_modules')
    var staging = path.resolve(node_modules, '.staging')
    postInstallSteps.push(
      [this.newTracker(log, 'rollbackFailedOptional', 1)],
      [this, this.rollbackFailedOptional, staging, this.todo],
      [this, this.finishTracker, 'rollbackFailedOptional'],
      [this, this.commit, staging, this.todo],
 
      [this, this.runPostinstallTopLevelLifecycles],
      [this, this.finishTracker, 'runTopLevelLifecycles'])
    if (getSaveType(this.args)) {
      postInstallSteps.push(
        [this, this.saveToDependencies])
    }
  }
  postInstallSteps.push(
    [this, this.printInstalled])
 
  var self = this
  chain(installSteps, function (installEr) {
    if (installEr) self.failing = true
    chain(postInstallSteps, function (postInstallEr) {
      if (self.idealTree) {
        self.idealTree.warnings.forEach(function (warning) {
          if (warning.code === 'EPACKAGEJSON' && self.global) return
          if (warning.code === 'ENOTDIR') return
          var output = errorMessage(warning)
          output.summary.forEach(function (logline) {
            log.warn.apply(log, logline)
          })
          output.detail.forEach(function (logline) {
            log.verbose.apply(log, logline)
          })
        })
      }
      if (installEr && postInstallEr) {
        var msg = errorMessage(postInstallEr)
        msg.summary.forEach(function (logline) {
          log.warn.apply(log, logline)
        })
        msg.detail.forEach(function (logline) {
          log.verbose.apply(log, logline)
        })
      }
      cb(installEr || postInstallEr, self.getInstalledModules(), self.idealTree)
    })
  })
}
 
Installer.prototype.loadArgMetadata = function (next) {
  var self = this
  getAllMetadata(this.args, this.currentTree, process.cwd(), iferr(next, function (args) {
    self.args = args
    next()
  }))
}
 
Installer.prototype.newTracker = function (tracker, name, size) {
  validate('OS', [tracker, name])
  if (size) validate('N', [size])
  this.progress[name] = tracker.newGroup(name, size)
  var self = this
  return function (next) {
    self.progress[name].silly(name, 'Starting')
    next()
  }
}
 
Installer.prototype.finishTracker = function (name, cb) {
  validate('SF', arguments)
  this.progress[name].silly(name, 'Finishing')
  this.progress[name].finish()
  cb()
}
 
Installer.prototype.loadCurrentTree = function (cb) {
  validate('F', arguments)
  log.silly('install', 'loadCurrentTree')
  var todo = []
  if (this.global) {
    todo.push([this, this.readGlobalPackageData])
  } else {
    todo.push([this, this.readLocalPackageData])
  }
  todo.push(
    [this, this.normalizeTree, log.newGroup('normalizeTree')])
  chain(todo, cb)
}
 
Installer.prototype.loadIdealTree = function (cb) {
  validate('F', arguments)
  log.silly('install', 'loadIdealTree')
 
  chain([
    [this.newTracker(this.progress.loadIdealTree, 'cloneCurrentTree')],
    [this, this.cloneCurrentTreeToIdealTree],
    [this, this.finishTracker, 'cloneCurrentTree'],
 
    [this.newTracker(this.progress.loadIdealTree, 'loadShrinkwrap')],
    [this, this.loadShrinkwrap],
    [this, this.finishTracker, 'loadShrinkwrap'],
 
    [this.newTracker(this.progress.loadIdealTree, 'loadAllDepsIntoIdealTree', 10)],
    [this, this.loadAllDepsIntoIdealTree],
    [this, this.finishTracker, 'loadAllDepsIntoIdealTree'],
 
    // TODO: Remove this (should no longer be necessary, instead counter productive)
    [this, function (next) { recalculateMetadata(this.idealTree, log, next) }]
  ], cb)
}
 
Installer.prototype.loadAllDepsIntoIdealTree = function (cb) {
  validate('F', arguments)
  log.silly('install', 'loadAllDepsIntoIdealTree')
  var saveDeps = getSaveType(this.args)
 
  var cg = this.progress.loadAllDepsIntoIdealTree
  var installNewModules = !!this.args.length
  var steps = []
 
  if (installNewModules) {
    steps.push([validateArgs, this.idealTree, this.args])
    steps.push([loadRequestedDeps, this.args, this.idealTree, saveDeps, cg.newGroup('loadRequestedDeps')])
  } else {
    if (this.prod) {
      steps.push(
        [loadDeps, this.idealTree, cg.newGroup('loadDeps')])
    }
    if (this.dev) {
      steps.push(
        [loadDevDeps, this.idealTree, cg.newGroup('loadDevDeps')])
    }
  }
  steps.push(
    [loadExtraneous.andResolveDeps, this.idealTree, cg.newGroup('loadExtraneous')])
  chain(steps, cb)
}
 
Installer.prototype.generateActionsToTake = function (cb) {
  validate('F', arguments)
  log.silly('install', 'generateActionsToTake')
  var cg = this.progress.generateActionsToTake
  chain([
    [validateTree, this.idealTree, cg.newGroup('validateTree')],
    [diffTrees, this.currentTree, this.idealTree, this.differences, cg.newGroup('diffTrees')],
    [this, this.computeLinked],
    [filterInvalidActions, this.where, this.differences],
    [checkPermissions, this.differences],
    [decomposeActions, this.differences, this.todo]
  ], cb)
}
 
Installer.prototype.computeLinked = function (cb) {
  validate('F', arguments)
  if (!this.link || this.global) return cb()
  var linkTodoList = []
  var self = this
  asyncMap(this.differences, function (action, next) {
    var cmd = action[0]
    var pkg = action[1]
    if (cmd !== 'add' && cmd !== 'update') return next()
    var isReqByTop = pkg.requiredBy.filter(function (mod) { return mod.isTop }).length
    var isReqByUser = pkg.userRequired
    var isExtraneous = pkg.requiredBy.length === 0
    if (!isReqByTop && !isReqByUser && !isExtraneous) return next()
    isLinkable(pkg, function (install, link) {
      if (install) linkTodoList.push(['global-install', pkg])
      if (link) linkTodoList.push(['global-link', pkg])
      if (install || link) removeObsoleteDep(pkg)
      next()
    })
  }, function () {
    if (linkTodoList.length === 0) return cb()
    self.differences.length = 0
    Array.prototype.push.apply(self.differences, linkTodoList)
    diffTrees(self.currentTree, self.idealTree, self.differences, log.newGroup('d2'), cb)
  })
}
 
function isLinkable (pkg, cb) {
  var globalPackage = path.resolve(npm.globalPrefix, 'lib', 'node_modules', moduleName(pkg))
  var globalPackageJson = path.resolve(globalPackage, 'package.json')
  fs.stat(globalPackage, function (er) {
    if (er) return cb(true, true)
    fs.readFile(globalPackageJson, function (er, data) {
      var json = parseJSON.noExceptions(data)
      cb(false, json && json.version === pkg.package.version)
    })
  })
}
 
Installer.prototype.executeActions = function (cb) {
  validate('F', arguments)
  log.silly('install', 'executeActions')
  var todo = this.todo
  var cg = this.progress.executeActions
 
  var node_modules = path.resolve(this.where, 'node_modules')
  var staging = path.resolve(node_modules, '.staging')
  var steps = []
  var trackLifecycle = cg.newGroup('lifecycle')
 
  cb = unlockCB(node_modules, '.staging', cb)
 
  steps.push(
    [doSerialActions, 'global-install', staging, todo, trackLifecycle.newGroup('global-install')],
    [doParallelActions, 'fetch', staging, todo, cg.newGroup('fetch', 10)],
    [lock, node_modules, '.staging'],
    [rimraf, staging],
    [mkdirp, staging],
    [doParallelActions, 'extract', staging, todo, cg.newGroup('extract', 10)],
    [doParallelActions, 'preinstall', staging, todo, trackLifecycle.newGroup('preinstall')],
    [doReverseSerialActions, 'remove', staging, todo, cg.newGroup('remove')],
    [doSerialActions, 'move', staging, todo, cg.newGroup('move')],
    [doSerialActions, 'finalize', staging, todo, cg.newGroup('finalize')],
    [doSerialActions, 'build', staging, todo, trackLifecycle.newGroup('build')],
    [doSerialActions, 'global-link', staging, todo, trackLifecycle.newGroup('global-link')],
    [doParallelActions, 'update-linked', staging, todo, trackLifecycle.newGroup('update-linked')],
    [doSerialActions, 'install', staging, todo, trackLifecycle.newGroup('install')],
    [doSerialActions, 'postinstall', staging, todo, trackLifecycle.newGroup('postinstall')])
 
  var self = this
  chain(steps, function (er) {
    if (!er || self.rollback) {
      rimraf(staging, function () { cb(er) })
    } else {
      cb(er)
    }
  })
}
 
Installer.prototype.rollbackFailedOptional = function (staging, actionsToRun, cb) {
  if (!this.rollback) return cb()
  var failed = actionsToRun.map(function (action) {
    return action[1]
  }).filter(function (pkg) {
    return pkg.failed && pkg.rollback
  })
  var top = this.currentTree && this.currentTree.path
  asyncMap(failed, function (pkg, next) {
    asyncMap(pkg.rollback, function (rollback, done) {
      rollback(top, staging, pkg, done)
    }, next)
  }, cb)
}
 
Installer.prototype.commit = function (staging, actionsToRun, cb) {
  var toCommit = actionsToRun.map(function (action) { return action[1] }).filter(function (pkg) { return !pkg.failed && pkg.commit })
  asyncMap(toCommit, function (pkg, next) {
    asyncMap(pkg.commit, function (commit, done) {
      commit(staging, pkg, done)
    }, function () {
      pkg.commit = []
      next.apply(null, arguments)
    })
  }, cb)
}
 
Installer.prototype.runPreinstallTopLevelLifecycles = function (cb) {
  validate('F', arguments)
  if (this.failing) return cb()
  if (!this.topLevelLifecycles) return cb()
  log.silly('install', 'runPreinstallTopLevelLifecycles')
  var steps = []
  var trackLifecycle = this.progress.runTopLevelLifecycles
 
  steps.push(
    [doOneAction, 'preinstall', this.idealTree.path, this.idealTree, trackLifecycle.newGroup('preinstall:.')]
  )
  chain(steps, cb)
}
 
Installer.prototype.runPostinstallTopLevelLifecycles = function (cb) {
  validate('F', arguments)
  if (this.failing) return cb()
  if (!this.topLevelLifecycles) return cb()
  log.silly('install', 'runPostinstallTopLevelLifecycles')
  var steps = []
  var trackLifecycle = this.progress.runTopLevelLifecycles
 
  steps.push(
    [doOneAction, 'build', this.idealTree.path, this.idealTree, trackLifecycle.newGroup('build:.')],
    [doOneAction, 'install', this.idealTree.path, this.idealTree, trackLifecycle.newGroup('install:.')],
    [doOneAction, 'postinstall', this.idealTree.path, this.idealTree, trackLifecycle.newGroup('postinstall:.')])
  if (this.dev) {
    steps.push(
      [doOneAction, 'prepare', this.idealTree.path, this.idealTree, trackLifecycle.newGroup('prepare')])
  }
  chain(steps, cb)
}
 
Installer.prototype.saveToDependencies = function (cb) {
  validate('F', arguments)
  if (this.failing) return cb()
  log.silly('install', 'saveToDependencies')
  saveRequested(this.args, this.idealTree, cb)
}
 
Installer.prototype.readGlobalPackageData = function (cb) {
  validate('F', arguments)
  log.silly('install', 'readGlobalPackageData')
  var self = this
  this.loadArgMetadata(iferr(cb, function () {
    mkdirp(self.where, iferr(cb, function () {
      var pkgs = {}
      self.args.forEach(function (pkg) {
        pkgs[pkg.name] = true
      })
      readPackageTree(self.where, function (ctx, kid) { return ctx.parent || pkgs[kid] }, iferr(cb, function (currentTree) {
        self.currentTree = currentTree
        return cb()
      }))
    }))
  }))
}
 
Installer.prototype.readLocalPackageData = function (cb) {
  validate('F', arguments)
  log.silly('install', 'readLocalPackageData')
  var self = this
  mkdirp(this.where, iferr(cb, function () {
    readPackageTree(self.where, iferr(cb, function (currentTree) {
      self.currentTree = currentTree
      self.currentTree.warnings = []
      if (currentTree.error && currentTree.error.code === 'EJSONPARSE') {
        return cb(currentTree.error)
      }
      if (!self.noPackageJsonOk && !currentTree.package) {
        log.error('install', "Couldn't read dependencies")
        var er = new Error("ENOENT, open '" + path.join(self.where, 'package.json') + "'")
        er.code = 'ENOPACKAGEJSON'
        er.errno = 34
        return cb(er)
      }
      if (!currentTree.package) currentTree.package = {}
      readShrinkwrap(currentTree, function (err) {
        if (err) {
          cb(err)
        } else {
          self.loadArgMetadata(cb)
        }
      })
    }))
  }))
}
 
Installer.prototype.cloneCurrentTreeToIdealTree = function (cb) {
  validate('F', arguments)
  log.silly('install', 'cloneCurrentTreeToIdealTree')
  this.idealTree = copyTree(this.currentTree)
  this.idealTree.warnings = []
  cb()
}
 
Installer.prototype.loadShrinkwrap = function (cb) {
  validate('F', arguments)
  log.silly('install', 'loadShrinkwrap')
  var installNewModules = !!this.args.length
  if (installNewModules) {
    readShrinkwrap(this.idealTree, cb)
  } else {
    readShrinkwrap.andInflate(this.idealTree, cb)
  }
}
 
Installer.prototype.normalizeTree = function (log, cb) {
  validate('OF', arguments)
  log.silly('install', 'normalizeTree')
  recalculateMetadata(this.currentTree, log, iferr(cb, function (tree) {
    tree.children.forEach(function (child) {
      if (child.requiredBy.length === 0) {
        child.existing = true
      }
    })
    cb(null, tree)
  }))
}
 
Installer.prototype.getInstalledModules = function () {
  return this.differences.filter(function (action) {
    var mutation = action[0]
    return (mutation === 'add' || mutation === 'update')
  }).map(function (action) {
    var child = action[1]
    return [child.package._id, child.path]
  })
}
 
Installer.prototype.printInstalled = function (cb) {
  validate('F', arguments)
  log.silly('install', 'printInstalled')
  var self = this
  this.differences.forEach(function (action) {
    var mutation = action[0]
    var child = action[1]
    var name = packageId(child)
    var where = path.relative(self.where, child.path)
    if (mutation === 'remove') {
      output('- ' + name + ' ' + where)
    } else if (mutation === 'move') {
      var oldWhere = path.relative(self.where, child.fromPath)
      output(name + ' ' + oldWhere + ' -> ' + where)
    }
  })
  var addedOrMoved = this.differences.filter(function (action) {
    var mutation = action[0]
    var child = action[1]
    return !child.failed && (mutation === 'add' || mutation === 'update')
  }).map(function (action) {
    var child = action[1]
    return child.path
  })
  if (!addedOrMoved.length) return cb()
  // TODO: remove the recalculateMetadata, should not be needed
  recalculateMetadata(this.idealTree, log, iferr(cb, function (tree) {
    // These options control both how installs happen AND how `ls` shows output.
    // Something like `npm install --production` only installs production deps.
    // By contrast `npm install --production foo` installs `foo` and the
    // `production` option is ignored. But when it comes time for `ls` to show
    // its output, it excludes the thing we just installed because that flag.
    // The summary output we get should be unfiltered, showing everything
    // installed, so we clear these options before calling `ls`.
    npm.config.set('production', false)
    npm.config.set('dev', false)
    npm.config.set('only', '')
    npm.config.set('also', '')
    ls.fromTree(self.where, tree, addedOrMoved, false, andIgnoreErrors(cb))
  }))
}
 
Installer.prototype.debugActions = function (name, actionListName, cb) {
  validate('SSF', arguments)
  var actionsToLog = this[actionListName]
  log.silly(name, 'action count', actionsToLog.length)
  actionsToLog.forEach(function (action) {
    log.silly(name, action.map(function (value) {
      return (value && value.package) ? packageId(value) : value
    }).join(' '))
  })
  cb()
}
 
// This takes an object and a property name instead of a value to allow us
// to define the arguments for use by chain before the property exists yet.
Installer.prototype.debugTree = function (name, treeName, cb) {
  validate('SSF', arguments)
  log.silly(name, this.prettify(this[treeName]).trim())
  cb()
}
 
Installer.prototype.prettify = function (tree) {
  validate('O', arguments)
  var seen = {}
  function byName (aa, bb) {
    return packageId(aa).localeCompare(packageId(bb))
  }
  function expandTree (tree) {
    seen[tree.path] = true
    return {
      label: packageId(tree),
      nodes: tree.children.filter(function (tree) { return !seen[tree.path] }).sort(byName).map(expandTree)
    }
  }
  return archy(expandTree(tree), '', { unicode: npm.config.get('unicode') })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/link.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/link.js

Statements: 18.7% (23 / 123)      Branches: 0% (0 / 65)      Functions: 0% (0 / 22)      Lines: 20.54% (23 / 112)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199      1 1 1 1 1 1 1 1 1 1 1   1   1           1                 1                                               1               1             1                                                                                         1                                     1             1                                                     1                                 1                        
// link with no args: symlink the folder to the global location
// link with package arg: symlink the global to the local
 
var npm = require('./npm.js')
var symlink = require('./utils/link.js')
var fs = require('graceful-fs')
var log = require('npmlog')
var asyncMap = require('slide').asyncMap
var chain = require('slide').chain
var path = require('path')
var build = require('./build.js')
var npa = require('npm-package-arg')
var usage = require('./utils/usage')
var output = require('./utils/output.js')
 
module.exports = link
 
link.usage = usage(
  'link',
  'npm link (in package dir)' +
  '\nnpm link [<@scope>/]<pkg>[@<version>]'
)
 
link.completion = function (opts, cb) {
  var dir = npm.globalDir
  fs.readdir(dir, function (er, files) {
    cb(er, files.filter(function (f) {
      return !f.match(/^[\._-]/)
    }))
  })
}
 
function link (args, cb) {
  if (process.platform === 'win32') {
    var semver = require('semver')
    if (!semver.gte(process.version, '0.7.9')) {
      var msg = 'npm link not supported on windows prior to node 0.7.9'
      var e = new Error(msg)
      e.code = 'ENOTSUP'
      e.errno = require('constants').ENOTSUP
      return cb(e)
    }
  }
 
  if (npm.config.get('global')) {
    return cb(new Error(
      'link should never be --global.\n' +
      'Please re-run this command with --local'
    ))
  }
 
  if (args.length === 1 && args[0] === '.') args = []
  if (args.length) return linkInstall(args, cb)
  linkPkg(npm.prefix, cb)
}
 
function parentFolder (id, folder) {
  if (id[0] === '@') {
    return path.resolve(folder, '..', '..')
  } else {
    return path.resolve(folder, '..')
  }
}
 
function linkInstall (pkgs, cb) {
  asyncMap(pkgs, function (pkg, cb) {
    var t = path.resolve(npm.globalDir, '..')
    var pp = path.resolve(npm.globalDir, pkg)
    var rp = null
    var target = path.resolve(npm.dir, pkg)
 
    function n (er, data) {
      if (er) return cb(er, data)
      // we want the ONE thing that was installed into the global dir
      var installed = data.filter(function (info) {
        var id = info[0]
        var folder = info[1]
        return parentFolder(id, folder) === npm.globalDir
      })
      var id = installed[0][0]
      pp = installed[0][1]
      var what = npa(id)
      pkg = what.name
      target = path.resolve(npm.dir, pkg)
      next()
    }
 
    // if it's a folder, a random not-installed thing, or not a scoped package,
    // then link or install it first
    if (pkg[0] !== '@' && (pkg.indexOf('/') !== -1 || pkg.indexOf('\\') !== -1)) {
      return fs.lstat(path.resolve(pkg), function (er, st) {
        if (er || !st.isDirectory()) {
          npm.commands.install(t, pkg, n)
        } else {
          rp = path.resolve(pkg)
          linkPkg(rp, n)
        }
      })
    }
 
    fs.lstat(pp, function (er, st) {
      if (er) {
        rp = pp
        return npm.commands.install(t, [pkg], n)
      } else if (!st.isSymbolicLink()) {
        rp = pp
        next()
      } else {
        return fs.realpath(pp, function (er, real) {
          if (er) log.warn('invalid symbolic link', pkg)
          else rp = real
          next()
        })
      }
    })
 
    function next () {
      if (npm.config.get('dry-run')) return resultPrinter(pkg, pp, target, rp, cb)
      chain(
        [
          [ function (cb) {
            log.verbose('link', 'symlinking %s to %s', pp, target)
            cb()
          } ],
          [symlink, pp, target],
          // do not run any scripts
          rp && [build, [target], npm.config.get('global'), build._noLC, true],
          [resultPrinter, pkg, pp, target, rp]
        ],
        cb
      )
    }
  }, cb)
}
 
function linkPkg (folder, cb_) {
  var me = folder || npm.prefix
  var readJson = require('read-package-json')
 
  log.verbose('linkPkg', folder)
 
  readJson(path.resolve(me, 'package.json'), function (er, d) {
    function cb (er) {
      return cb_(er, [[d && d._id, target, null, null]])
    }
    if (er) return cb(er)
    if (!d.name) {
      er = new Error('Package must have a name field to be linked')
      return cb(er)
    }
    if (npm.config.get('dry-run')) return resultPrinter(path.basename(me), me, target, cb)
    var target = path.resolve(npm.globalDir, d.name)
    symlink(me, target, false, true, function (er) {
      if (er) return cb(er)
      log.verbose('link', 'build target', target)
      // also install missing dependencies.
      npm.commands.install(me, [], function (er) {
        if (er) return cb(er)
        // build the global stuff.  Don't run *any* scripts, because
        // install command already will have done that.
        build([target], true, build._noLC, true, function (er) {
          if (er) return cb(er)
          resultPrinter(path.basename(me), me, target, cb)
        })
      })
    })
  })
}
 
function resultPrinter (pkg, src, dest, rp, cb) {
  if (typeof cb !== 'function') {
    cb = rp
    rp = null
  }
  var where = dest
  rp = (rp || '').trim()
  src = (src || '').trim()
  // XXX If --json is set, then look up the data from the package.json
  if (npm.config.get('parseable')) {
    return parseableOutput(dest, rp || src, cb)
  }
  if (rp === src) rp = null
  output(where + ' -> ' + src + (rp ? ' -> ' + rp : ''))
  cb()
}
 
function parseableOutput (dest, rp, cb) {
  // XXX this should match ls --parseable and install --parseable
  // look up the data from package.json, format it the same way.
  //
  // link is always effectively 'long', since it doesn't help much to
  // *just* print the target folder.
  // However, we don't actually ever read the version number, so
  // the second field is always blank.
  output(dest + '::' + rp)
  cb()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/logout.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/logout.js

Statements: 29.63% (8 / 27)      Branches: 0% (0 / 12)      Functions: 0% (0 / 4)      Lines: 33.33% (8 / 24)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 451   1 1   1 1   1   1                 1                                                  
module.exports = logout
 
var dezalgo = require('dezalgo')
var log = require('npmlog')
 
var npm = require('./npm.js')
var mapToRegistry = require('./utils/map-to-registry.js')
 
logout.usage = 'npm logout [--registry=<url>] [--scope=<@scope>]'
 
function afterLogout (normalized, cb) {
  var scope = npm.config.get('scope')
 
  if (scope) npm.config.del(scope + ':registry')
 
  npm.config.clearCredentialsByURI(normalized)
  npm.config.save('user', cb)
}
 
function logout (args, cb) {
  cb = dezalgo(cb)
 
  mapToRegistry('/', npm.config, function (err, uri, auth, normalized) {
    if (err) return cb(err)
 
    if (auth.token) {
      log.verbose('logout', 'clearing session token for', normalized)
      npm.registry.logout(normalized, { auth: auth }, function (err) {
        if (err) return cb(err)
 
        afterLogout(normalized, cb)
      })
    } else if (auth.username || auth.password) {
      log.verbose('logout', 'clearing user credentials for', normalized)
 
      afterLogout(normalized, cb)
    } else {
      cb(new Error(
        'Not logged in to', normalized + ',', "so can't log out."
      ))
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/ls.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/ls.js

Statements: 8.41% (29 / 345)      Branches: 0.33% (1 / 299)      Functions: 0% (0 / 31)      Lines: 9.32% (29 / 311)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514            14   14 14 14 14 14 14 14 14 14 14 14 14 14                         1                     1           1                                                                                                                                   1                       1                                       1             1       1                                                                                                                                                                                       1                                                 1                                                                                                                 1         1                                                                                                                                                                                                                               1                                 1                         1                                                                  
// show the installed versions of packages
//
// --parseable creates output like this:
// <fullpath>:<name@ver>:<realpath>:<flags>
// Flags are a :-separated list of zero or more indicators
 
module.exports = exports = ls
 
var path = require('path')
var url = require('url')
var readPackageTree = require('read-package-tree')
var log = require('npmlog')
var archy = require('archy')
var semver = require('semver')
var color = require('ansicolors')
var npa = require('npm-package-arg')
var iferr = require('iferr')
var sortedObject = require('sorted-object')
var extend = Object.assign || require('util')._extend
var npm = require('./npm.js')
var mutateIntoLogicalTree = require('./install/mutate-into-logical-tree.js')
var recalculateMetadata = require('./install/deps.js').recalculateMetadata
var packageId = require('./utils/package-id.js')
var usage = require('./utils/usage')
var output = require('./utils/output.js')
 
ls.usage = usage(
  'ls',
  'npm ls [[<@scope>/]<pkg> ...]'
)
 
ls.completion = require('./utils/completion/installed-deep.js')
 
function ls (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
  var dir = path.resolve(npm.dir, '..')
  readPackageTree(dir, andRecalculateMetadata(iferr(cb, function (physicalTree) {
    lsFromTree(dir, physicalTree, args, silent, cb)
  })))
}
 
function andRecalculateMetadata (next) {
  return function (er, tree) {
    recalculateMetadata(tree || {}, log, next)
  }
}
 
function inList (list, value) {
  return list.indexOf(value) !== -1
}
 
var lsFromTree = ls.fromTree = function (dir, physicalTree, args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
 
  // npm ls 'foo@~1.3' bar 'baz@<2'
  if (!args) {
    args = []
  } else {
    args = args.map(function (a) {
      var p = npa(a)
      var name = p.name
      // When version spec is missing, we'll skip using it when filtering.
      // Otherwise, `semver.validRange` would return '*', which won't
      // match prerelease versions.
      var ver = (p.rawSpec &&
                 (semver.validRange(p.rawSpec) || ''))
      return [ name, ver, a ]
    })
  }
 
  var data = mutateIntoLogicalTree.asReadInstalled(physicalTree)
 
  pruneNestedExtraneous(data)
  filterByEnv(data)
  var unlooped = filterFound(unloop(data), args)
  var lite = getLite(unlooped)
 
  if (silent) return cb(null, data, lite)
 
  var long = npm.config.get('long')
  var json = npm.config.get('json')
  var out
  if (json) {
    var seen = []
    var d = long ? unlooped : lite
    // the raw data can be circular
    out = JSON.stringify(d, function (k, o) {
      if (typeof o === 'object') {
        if (inList(seen, o)) return '[Circular]'
        seen.push(o)
      }
      return o
    }, 2)
  } else if (npm.config.get('parseable')) {
    out = makeParseable(unlooped, long, dir)
  } else if (data) {
    out = makeArchy(unlooped, long, dir)
  }
  output(out)
 
  if (args.length && !data._found) process.exitCode = 1
 
  var er
  // if any errors were found, then complain and exit status 1
  if (lite.problems && lite.problems.length) {
    er = lite.problems.join('\n')
  }
  cb(er, data, lite)
}
 
function pruneNestedExtraneous (data, visited) {
  visited = visited || []
  visited.push(data)
  for (var i in data.dependencies) {
    if (data.dependencies[i].extraneous) {
      data.dependencies[i].dependencies = {}
    } else if (visited.indexOf(data.dependencies[i]) === -1) {
      pruneNestedExtraneous(data.dependencies[i], visited)
    }
  }
}
 
function filterByEnv (data) {
  var dev = npm.config.get('dev') || /^dev(elopment)?$/.test(npm.config.get('only'))
  var production = npm.config.get('production') || /^prod(uction)?$/.test(npm.config.get('only'))
  var dependencies = {}
  var devKeys = Object.keys(data.devDependencies || [])
  var prodKeys = Object.keys(data._dependencies || [])
  Object.keys(data.dependencies).forEach(function (name) {
    if (!dev && inList(devKeys, name) && data.dependencies[name].missing) {
      return
    }
 
    if ((dev && inList(devKeys, name)) ||            // only --dev
        (production && inList(prodKeys, name)) ||    // only --production
        (!dev && !production)) {                            // no --production|--dev|--only=xxx
      dependencies[name] = data.dependencies[name]
    }
  })
  data.dependencies = dependencies
}
 
function alphasort (a, b) {
  a = a.toLowerCase()
  b = b.toLowerCase()
  return a > b ? 1
       : a < b ? -1 : 0
}
 
function isCruft (data) {
  return data.extraneous && data.error && data.error.code === 'ENOTDIR'
}
 
function getLite (data, noname, depth) {
  var lite = {}
 
  if (isCruft(data)) return lite
 
  var maxDepth = npm.config.get('depth')
 
  if (typeof depth === 'undefined') depth = 0
  if (!noname && data.name) lite.name = data.name
  if (data.version) lite.version = data.version
  if (data.extraneous) {
    lite.extraneous = true
    lite.problems = lite.problems || []
    lite.problems.push('extraneous: ' + packageId(data) + ' ' + (data.path || ''))
  }
 
  if (data.error && data.path !== path.resolve(npm.globalDir, '..') &&
      (data.error.code !== 'ENOENT' || noname)) {
    lite.invalid = true
    lite.problems = lite.problems || []
    var message = data.error.message
    lite.problems.push('error in ' + data.path + ': ' + message)
  }
 
  if (data._from) {
    lite.from = data._from
  }
 
  if (data._resolved) {
    lite.resolved = data._resolved
  }
 
  if (data.invalid) {
    lite.invalid = true
    lite.problems = lite.problems || []
    lite.problems.push('invalid: ' +
                       packageId(data) +
                       ' ' + (data.path || ''))
  }
 
  if (data.peerInvalid) {
    lite.peerInvalid = true
    lite.problems = lite.problems || []
    lite.problems.push('peer dep not met: ' +
                       packageId(data) +
                       ' ' + (data.path || ''))
  }
 
  var deps = (data.dependencies && Object.keys(data.dependencies)) || []
  if (deps.length) {
    lite.dependencies = deps.map(function (d) {
      var dep = data.dependencies[d]
      if (dep.missing && !dep.optional) {
        lite.problems = lite.problems || []
        var p
        if (data.depth > maxDepth) {
          p = 'max depth reached: '
        } else {
          p = 'missing: '
        }
        p += d + '@' + dep.requiredBy +
            ', required by ' +
            packageId(data)
        lite.problems.push(p)
        return [d, { required: dep.requiredBy, missing: true }]
      } else if (dep.peerMissing) {
        lite.problems = lite.problems || []
        dep.peerMissing.forEach(function (missing) {
          var pdm = 'peer dep missing: ' +
              missing.requires +
              ', required by ' +
              missing.requiredBy
          lite.problems.push(pdm)
        })
        return [d, { required: dep, peerMissing: true }]
      } else if (npm.config.get('json')) {
        if (depth === maxDepth) delete dep.dependencies
        return [d, getLite(dep, true, depth + 1)]
      }
      return [d, getLite(dep, true)]
    }).reduce(function (deps, d) {
      if (d[1].problems) {
        lite.problems = lite.problems || []
        lite.problems.push.apply(lite.problems, d[1].problems)
      }
      deps[d[0]] = d[1]
      return deps
    }, {})
  }
  return lite
}
 
function unloop (root) {
  var queue = [root]
  var seen = {}
  seen[root.path] = true
 
  while (queue.length) {
    var current = queue.shift()
    var deps = current.dependencies = current.dependencies || {}
    Object.keys(deps).forEach(function (d) {
      var dep = deps[d]
      if (dep.missing) return
      if (dep.path && seen[dep.path]) {
        dep = deps[d] = extend({}, dep)
        dep.dependencies = {}
        dep._deduped = path.relative(root.path, dep.path).replace(/node_modules\//g, '')
        return
      }
      seen[dep.path] = true
      queue.push(dep)
    })
  }
 
  return root
}
 
function filterFound (root, args) {
  if (!args.length) return root
  if (!root.dependencies) return root
 
  // Mark all deps
  var toMark = [root]
  while (toMark.length) {
    var markPkg = toMark.shift()
    var markDeps = markPkg.dependencies
    if (!markDeps) continue
    Object.keys(markDeps).forEach(function (depName) {
      var dep = markDeps[depName]
      if (dep.peerMissing) return
      dep._parent = markPkg
      for (var ii = 0; ii < args.length; ii++) {
        var argName = args[ii][0]
        var argVersion = args[ii][1]
        var argRaw = args[ii][2]
        var found
        if (depName === argName && argVersion) {
          found = semver.satisfies(dep.version, argVersion, true)
        } else if (depName === argName) {
          // If version is missing from arg, just do a name match.
          found = true
        } else if (dep.path === argRaw) {
          found = true
        }
        if (found) {
          dep._found = 'explicit'
          var parent = dep._parent
          while (parent && !parent._found && !parent._deduped) {
            parent._found = 'implicit'
            parent = parent._parent
          }
          break
        }
      }
      toMark.push(dep)
    })
  }
  var toTrim = [root]
  while (toTrim.length) {
    var trimPkg = toTrim.shift()
    var trimDeps = trimPkg.dependencies
    if (!trimDeps) continue
    trimPkg.dependencies = {}
    Object.keys(trimDeps).forEach(function (name) {
      var dep = trimDeps[name]
      if (!dep._found) return
      if (dep._found === 'implicit' && dep._deduped) return
      trimPkg.dependencies[name] = dep
      toTrim.push(dep)
    })
  }
  return root
}
 
function makeArchy (data, long, dir) {
  var out = makeArchy_(data, long, dir, 0)
  return archy(out, '', { unicode: npm.config.get('unicode') })
}
 
function makeArchy_ (data, long, dir, depth, parent, d) {
  if (data.missing) {
    if (depth - 1 <= npm.config.get('depth')) {
      // just missing
      var unmet = 'UNMET ' + (data.optional ? 'OPTIONAL ' : '') + 'DEPENDENCY'
      if (npm.color) {
        if (data.optional) {
          unmet = color.bgBlack(color.yellow(unmet))
        } else {
          unmet = color.bgBlack(color.red(unmet))
        }
      }
      data = unmet + ' ' + d + '@' + data.requiredBy
    } else {
      data = d + '@' + data.requiredBy
    }
    return data
  }
 
  var out = {}
  // the top level is a bit special.
  out.label = data._id || ''
  if (data._found === 'explicit' && data._id) {
    if (npm.color) {
      out.label = color.bgBlack(color.yellow(out.label.trim())) + ' '
    } else {
      out.label = out.label.trim() + ' '
    }
  }
  if (data.link) out.label += ' -> ' + data.link
 
  if (data._deduped) {
    if (npm.color) {
      out.label += ' ' + color.brightBlack('deduped')
    } else {
      out.label += ' deduped'
    }
  }
 
  if (data.invalid) {
    if (data.realName !== data.name) out.label += ' (' + data.realName + ')'
    var invalid = 'invalid'
    if (npm.color) invalid = color.bgBlack(color.red(invalid))
    out.label += ' ' + invalid
  }
 
  if (data.peerInvalid) {
    var peerInvalid = 'peer invalid'
    if (npm.color) peerInvalid = color.bgBlack(color.red(peerInvalid))
    out.label += ' ' + peerInvalid
  }
 
  if (data.peerMissing) {
    var peerMissing = 'UNMET PEER DEPENDENCY'
 
    if (npm.color) peerMissing = color.bgBlack(color.red(peerMissing))
    out.label = peerMissing + ' ' + out.label
  }
 
  if (data.extraneous && data.path !== dir) {
    var extraneous = 'extraneous'
    if (npm.color) extraneous = color.bgBlack(color.green(extraneous))
    out.label += ' ' + extraneous
  }
 
  if (data.error && depth) {
    var message = data.error.message
    if (message.indexOf('\n')) message = message.slice(0, message.indexOf('\n'))
    var error = 'error: ' + message
    if (npm.color) error = color.bgRed(color.brightWhite(error))
    out.label += ' ' + error
  }
 
  // add giturl to name@version
  if (data._resolved) {
    try {
      var type = npa(data._resolved).type
      var isGit = type === 'git' || type === 'hosted'
      if (isGit) {
        out.label += ' (' + data._resolved + ')'
      }
    } catch (ex) {
      // npa threw an exception then it ain't git so whatev
    }
  }
 
  if (long) {
    if (dir === data.path) out.label += '\n' + dir
    out.label += '\n' + getExtras(data, dir)
  } else if (dir === data.path) {
    if (out.label) out.label += ' '
    out.label += dir
  }
 
  // now all the children.
  out.nodes = []
  if (depth <= npm.config.get('depth')) {
    out.nodes = Object.keys(data.dependencies || {})
      .sort(alphasort).filter(function (d) {
        return !isCruft(data.dependencies[d])
      }).map(function (d) {
        return makeArchy_(sortedObject(data.dependencies[d]), long, dir, depth + 1, data, d)
      })
  }
 
  if (out.nodes.length === 0 && data.path === dir) {
    out.nodes = ['(empty)']
  }
 
  return out
}
 
function getExtras (data) {
  var extras = []
 
  if (data.description) extras.push(data.description)
  if (data.repository) extras.push(data.repository.url)
  if (data.homepage) extras.push(data.homepage)
  if (data._from) {
    var from = data._from
    if (from.indexOf(data.name + '@') === 0) {
      from = from.substr(data.name.length + 1)
    }
    var u = url.parse(from)
    if (u.protocol) extras.push(from)
  }
  return extras.join('\n')
}
 
function makeParseable (data, long, dir, depth, parent, d) {
  if (data._deduped) return []
  depth = depth || 0
  if (depth > npm.config.get('depth')) return [ makeParseable_(data, long, dir, depth, parent, d) ]
  return [ makeParseable_(data, long, dir, depth, parent, d) ]
    .concat(Object.keys(data.dependencies || {})
      .sort(alphasort).map(function (d) {
        return makeParseable(data.dependencies[d], long, dir, depth + 1, data, d)
      }))
    .filter(function (x) { return x })
    .join('\n')
}
 
function makeParseable_ (data, long, dir, depth, parent, d) {
  if (data.hasOwnProperty('_found') && data._found !== 'explicit') return ''
 
  if (data.missing) {
    if (depth < npm.config.get('depth')) {
      data = npm.config.get('long')
           ? path.resolve(parent.path, 'node_modules', d) +
             ':' + d + '@' + JSON.stringify(data.requiredBy) + ':INVALID:MISSING'
           : ''
    } else {
      data = path.resolve(dir || '', 'node_modules', d || '') +
             (npm.config.get('long')
             ? ':' + d + '@' + JSON.stringify(data.requiredBy) +
               ':' + // no realpath resolved
               ':MAXDEPTH'
             : '')
    }
 
    return data
  }
 
  if (!npm.config.get('long')) return data.path
 
  return data.path +
         ':' + (data._id || '') +
         ':' + (data.realPath !== data.path ? data.realPath : '') +
         (data.extraneous ? ':EXTRANEOUS' : '') +
         (data.error && data.path !== path.resolve(npm.globalDir, '..') ? ':ERROR' : '') +
         (data.invalid ? ':INVALID' : '') +
         (data.peerInvalid ? ':PEERINVALID' : '') +
         (data.peerMissing ? ':PEERINVALID:MISSING' : '')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/npm.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/npm.js

Statements: 30.51% (83 / 272)      Branches: 8.63% (12 / 139)      Functions: 34.15% (14 / 41)      Lines: 32.93% (81 / 246)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 4631     1                       1 1   1   1   1 1 1 1   1 1 1 1 1 1 1 1 1 1 1 1 1   1     50             1     1           1   1   1   1               1 1   1 1 87   1     1 87     1 1   1 302 340 340                                                                                                               302 27 27         1           1                         1 1 1 1   1             1                         1                                                     1                                                                                                                                                                                                                                                   1     4                   1     4           1                 1     4           1     4             1     1 4         1 1 1     4 4           1 302   296                                 1       1       1                          
;(function () {
  // windows: running 'npm blah' in this folder will invoke WSH, not node.
  /*globals WScript*/
  Iif (typeof WScript !== 'undefined') {
    WScript.echo(
      'npm does not work when run\n' +
      'with the Windows Scripting Host\n\n' +
      '"cd" to a different directory,\n' +
      'or type "npm.cmd <args>",\n' +
      'or type "node npm <args>".'
    )
    WScript.quit(1)
    return
  }
 
  var unsupported = require('../lib/utils/unsupported.js')
  unsupported.checkForBrokenNode()
 
  var gfs = require('graceful-fs')
  // Patch the global fs module here at the app level
  var fs = gfs.gracefulify(require('fs'))
 
  var EventEmitter = require('events').EventEmitter
  var npm = module.exports = new EventEmitter()
  var npmconf = require('./config/core.js')
  var log = require('npmlog')
 
  var tty = require('tty')
  var path = require('path')
  var abbrev = require('abbrev')
  var which = require('which')
  var glob = require('glob')
  var rimraf = require('rimraf')
  var lazyProperty = require('lazy-property')
  var parseJSON = require('./utils/parse-json.js')
  var aliases = require('./config/cmd-list').aliases
  var cmdList = require('./config/cmd-list').cmdList
  var plumbing = require('./config/cmd-list').plumbing
  var output = require('./utils/output.js')
  var startMetrics = require('./utils/metrics.js').start
 
  npm.config = {
    loaded: false,
    get: function () {
      throw new Error('npm.load() required')
    },
    set: function () {
      throw new Error('npm.load() required')
    }
  }
 
  npm.commands = {}
 
  // TUNING
  npm.limit = {
    fetch: 10,
    action: 10
  }
  // ***
 
  npm.rollbacks = []
 
  try {
    // startup, ok to do this synchronously
    var j = parseJSON(fs.readFileSync(
      path.join(__dirname, '../package.json')) + '')
    npm.version = j.version
  } catch (ex) {
    try {
      log.info('error reading version', ex)
    } catch (er) {}
    npm.version = ex
  }
 
  var commandCache = {}
  var aliasNames = Object.keys(aliases)
 
  var littleGuys = [ 'isntall', 'verison' ]
  var fullList = cmdList.concat(aliasNames).filter(function (c) {
    return plumbing.indexOf(c) === -1
  })
  var abbrevs = abbrev(fullList)
 
  // we have our reasons
  fullList = npm.fullList = fullList.filter(function (c) {
    return littleGuys.indexOf(c) === -1
  })
 
  var registryRefer
  var registryLoaded
 
  Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) {
    Object.defineProperty(npm.commands, c, { get: function () {
      Eif (!loaded) {
        throw new Error(
          'Call npm.load(config, cb) before using this command.\n' +
            'See the README.md or cli.js for example usage.'
        )
      }
      var a = npm.deref(c)
      if (c === 'la' || c === 'll') {
        npm.config.set('long', true)
      }
 
      npm.command = c
      if (commandCache[a]) return commandCache[a]
 
      var cmd = require(path.join(__dirname, a + '.js'))
 
      commandCache[a] = function () {
        var args = Array.prototype.slice.call(arguments, 0)
        if (typeof args[args.length - 1] !== 'function') {
          args.push(defaultCb)
        }
        if (args.length === 1) args.unshift([])
 
        // Options are prefixed by a hyphen-minus (-, \u2d).
        // Other dash-type chars look similar but are invalid.
        Array(args[0]).forEach(function (arg) {
          if (/^[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/.test(arg)) {
            log.error('arg', 'Argument starts with non-ascii dash, this is probably invalid:', arg)
          }
        })
 
        if (!registryRefer) {
          registryRefer = [a].concat(args[0]).map(function (arg) {
            // exclude anything that might be a URL, path, or private module
            // Those things will always have a slash in them somewhere
            if (arg && arg.match && arg.match(/\/|\\/)) {
              return '[REDACTED]'
            } else {
              return arg
            }
          }).filter(function (arg) {
            return arg && arg.match
          }).join(' ')
          if (registryLoaded) npm.registry.refer = registryRefer
        }
 
        cmd.apply(npm, args)
      }
 
      Object.keys(cmd).forEach(function (k) {
        commandCache[a][k] = cmd[k]
      })
 
      return commandCache[a]
    }, enumerable: fullList.indexOf(c) !== -1, configurable: true })
 
    // make css-case commands callable via camelCase as well
    if (c.match(/\-([a-z])/)) {
      addCommand(c.replace(/\-([a-z])/g, function (a, b) {
        return b.toUpperCase()
      }))
    }
  })
 
  function defaultCb (er, data) {
    log.disableProgress()
    if (er) console.error(er.stack || er.message)
    else output(data)
  }
 
  npm.deref = function (c) {
    if (!c) return ''
    if (c.match(/[A-Z]/)) {
      c = c.replace(/([A-Z])/g, function (m) {
        return '-' + m.toLowerCase()
      })
    }
    if (plumbing.indexOf(c) !== -1) return c
    var a = abbrevs[c]
    if (aliases[a]) a = aliases[a]
    return a
  }
 
  var loaded = false
  var loading = false
  var loadErr = null
  var loadListeners = []
 
  function loadCb (er) {
    loadListeners.forEach(function (cb) {
      process.nextTick(cb.bind(npm, er, npm))
    })
    loadListeners.length = 0
  }
 
  npm.load = function (cli, cb_) {
    if (!cb_ && typeof cli === 'function') {
      cb_ = cli
      cli = {}
    }
    if (!cb_) cb_ = function () {}
    if (!cli) cli = {}
    loadListeners.push(cb_)
    if (loaded || loadErr) return cb(loadErr)
    if (loading) return
    loading = true
    var onload = true
 
    function cb (er) {
      if (loadErr) return
      loadErr = er
      if (er) return cb_(er)
      if (npm.config.get('force')) {
        log.warn('using --force', 'I sure hope you know what you are doing.')
      }
      npm.config.loaded = true
      loaded = true
      loadCb(loadErr = er)
      onload = onload && npm.config.get('onload-script')
      if (onload) {
        try {
          require(onload)
        } catch (err) {
          log.warn('onload-script', 'failed to require onload script', onload)
          log.warn('onload-script', err)
        }
        onload = false
      }
    }
 
    log.pause()
 
    load(npm, cli, cb)
  }
 
  function load (npm, cli, cb) {
    which(process.argv[0], function (er, node) {
      if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) {
        log.verbose('node symlink', node)
        process.execPath = node
        process.installPrefix = path.resolve(node, '..', '..')
      }
 
      // look up configs
      var builtin = path.resolve(__dirname, '..', 'npmrc')
      npmconf.load(cli, builtin, function (er, config) {
        if (er === config) er = null
 
        npm.config = config
        if (er) return cb(er)
 
        // if the 'project' config is not a filename, and we're
        // not in global mode, then that means that it collided
        // with either the default or effective userland config
        if (!config.get('global') &&
            config.sources.project &&
            config.sources.project.type !== 'ini') {
          log.verbose(
            'config',
            'Skipping project config: %s. (matches userconfig)',
            config.localPrefix + '/.npmrc'
          )
        }
 
        // Include npm-version and node-version in user-agent
        var ua = config.get('user-agent') || ''
        ua = ua.replace(/\{node-version\}/gi, process.version)
        ua = ua.replace(/\{npm-version\}/gi, npm.version)
        ua = ua.replace(/\{platform\}/gi, process.platform)
        ua = ua.replace(/\{arch\}/gi, process.arch)
        config.set('user-agent', ua)
 
        if (config.get('metrics-registry') == null) {
          config.set('metrics-registry', config.get('registry'))
        }
 
        var color = config.get('color')
 
        log.level = config.get('loglevel')
        log.heading = config.get('heading') || 'npm'
        log.stream = config.get('logstream')
 
        switch (color) {
          case 'always':
            log.enableColor()
            npm.color = true
            break
          case false:
            log.disableColor()
            npm.color = false
            break
          default:
            if (process.stdout.isTTY) npm.color = true
            else if (!tty.isatty) npm.color = true
            else if (tty.isatty(1)) npm.color = true
            else npm.color = false
            break
        }
 
        if (config.get('unicode')) {
          log.enableUnicode()
        } else {
          log.disableUnicode()
        }
 
        if (config.get('progress') && (process.stderr.isTTY || (tty.isatty && tty.isatty(2)))) {
          log.enableProgress()
        } else {
          log.disableProgress()
        }
 
        glob(path.resolve(npm.cache, '_logs', '*-debug.log'), function (er, files) {
          if (er) return cb(er)
 
          while (files.length >= npm.config.get('logs-max')) {
            rimraf.sync(files[0])
            files.splice(0, 1)
          }
        })
 
        log.resume()
 
        var umask = npm.config.get('umask')
        npm.modes = {
          exec: parseInt('0777', 8) & (~umask),
          file: parseInt('0666', 8) & (~umask),
          umask: umask
        }
 
        var gp = Object.getOwnPropertyDescriptor(config, 'globalPrefix')
        Object.defineProperty(npm, 'globalPrefix', gp)
 
        var lp = Object.getOwnPropertyDescriptor(config, 'localPrefix')
        Object.defineProperty(npm, 'localPrefix', lp)
 
        config.set('scope', scopeifyScope(config.get('scope')))
        npm.projectScope = config.get('scope') ||
         scopeifyScope(getProjectScope(npm.prefix))
 
        // at this point the configs are all set.
        // go ahead and spin up the registry client.
        lazyProperty(npm, 'registry', function () {
          registryLoaded = true
          var CachingRegClient = require('./cache/caching-client.js')
          var registry = new CachingRegClient(npm.config)
          registry.version = npm.version
          registry.refer = registryRefer
          return registry
        })
 
        startMetrics()
 
        return cb(null, npm)
      })
    })
  }
 
  Object.defineProperty(npm, 'prefix',
    {
      get: function () {
        return npm.config.get('global') ? npm.globalPrefix : npm.localPrefix
      },
      set: function (r) {
        var k = npm.config.get('global') ? 'globalPrefix' : 'localPrefix'
        npm[k] = r
        return r
      },
      enumerable: true
    })
 
  Object.defineProperty(npm, 'bin',
    {
      get: function () {
        if (npm.config.get('global')) return npm.globalBin
        return path.resolve(npm.root, '.bin')
      },
      enumerable: true
    })
 
  Object.defineProperty(npm, 'globalBin',
    {
      get: function () {
        var b = npm.globalPrefix
        if (process.platform !== 'win32') b = path.resolve(b, 'bin')
        return b
      }
    })
 
  Object.defineProperty(npm, 'dir',
    {
      get: function () {
        if (npm.config.get('global')) return npm.globalDir
        return path.resolve(npm.prefix, 'node_modules')
      },
      enumerable: true
    })
 
  Object.defineProperty(npm, 'globalDir',
    {
      get: function () {
        return (process.platform !== 'win32')
             ? path.resolve(npm.globalPrefix, 'lib', 'node_modules')
             : path.resolve(npm.globalPrefix, 'node_modules')
      },
      enumerable: true
    })
 
  Object.defineProperty(npm, 'root',
    { get: function () { return npm.dir } })
 
  Object.defineProperty(npm, 'cache',
    { get: function () { return npm.config.get('cache') },
      set: function (r) { return npm.config.set('cache', r) },
      enumerable: true
    })
 
  var tmpFolder
  var rand = require('crypto').randomBytes(4).toString('hex')
  Object.defineProperty(npm, 'tmp',
    {
      get: function () {
        if (!tmpFolder) tmpFolder = 'npm-' + process.pid + '-' + rand
        return path.resolve(npm.config.get('tmp'), tmpFolder)
      },
      enumerable: true
    })
 
  // the better to repl you with
  Object.getOwnPropertyNames(npm.commands).forEach(function (n) {
    if (npm.hasOwnProperty(n) || n === 'config') return
 
    Object.defineProperty(npm, n, { get: function () {
      return function () {
        var args = Array.prototype.slice.call(arguments, 0)
        var cb = defaultCb
 
        if (args.length === 1 && Array.isArray(args[0])) {
          args = args[0]
        }
 
        if (typeof args[args.length - 1] === 'function') {
          cb = args.pop()
        }
        npm.commands[n](args, cb)
      }
    }, enumerable: false, configurable: true })
  })
 
  Iif (require.main === module) {
    require('../bin/npm-cli.js')
  }
 
  function scopeifyScope (scope) {
    return (!scope || scope[0] === '@') ? scope : ('@' + scope)
  }
 
  function getProjectScope (prefix) {
    try {
      var pkg = JSON.parse(fs.readFileSync(path.join(prefix, 'package.json')))
      if (typeof pkg.name !== 'string') return ''
      var sep = pkg.name.indexOf('/')
      if (sep === -1) return ''
      return pkg.name.slice(0, sep)
    } catch (ex) {
      return ''
    }
  }
})()
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/outdated.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/outdated.js

Statements: 12.2% (30 / 246)      Branches: 0% (0 / 171)      Functions: 0% (0 / 39)      Lines: 13.7% (30 / 219)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426                                2   2   2   2 2 2 2 2 2 2 2 2 2 2 2 2                     1       1                       1             1                                                                                                         1                                                             1                                           1                                             1                                                                                                                                                                                                                 1               1                     1                                             1                                             1                                                       1                                                            
/*
 
npm outdated [pkg]
 
Does the following:
 
1. check for a new version of pkg
 
If no packages are specified, then run for all installed
packages.
 
--parseable creates output like this:
<fullpath>:<name@wanted>:<name@installed>:<name@latest>
 
*/
 
module.exports = outdated
 
outdated.usage = 'npm outdated [[<@scope>/]<pkg> ...]'
 
outdated.completion = require('./utils/completion/installed-deep.js')
 
var os = require('os')
var url = require('url')
var path = require('path')
var log = require('npmlog')
var readPackageTree = require('read-package-tree')
var readJson = require('read-package-json')
var asyncMap = require('slide').asyncMap
var color = require('ansicolors')
var styles = require('ansistyles')
var table = require('text-table')
var semver = require('semver')
var npa = require('npm-package-arg')
var mutateIntoLogicalTree = require('./install/mutate-into-logical-tree.js')
var cache = require('./cache.js')
var npm = require('./npm.js')
var long = npm.config.get('long')
var mapToRegistry = require('./utils/map-to-registry.js')
var isExtraneous = require('./install/is-extraneous.js')
var recalculateMetadata = require('./install/deps.js').recalculateMetadata
var moduleName = require('./utils/module-name.js')
var output = require('./utils/output.js')
var ansiTrim = require('./utils/ansi-trim')
 
function uniqName (item) {
  return item[0].path + '|' + item[1] + '|' + item[7]
}
 
function uniq (list) {
  var uniqed = []
  var seen = {}
  list.forEach(function (item) {
    var name = uniqName(item)
    if (seen[name]) return
    seen[name] = true
    uniqed.push(item)
  })
  return uniqed
}
 
function andRecalculateMetadata (next) {
  return function (er, tree) {
    if (er) return next(er)
    recalculateMetadata(tree, log, next)
  }
}
 
function outdated (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
  var dir = path.resolve(npm.dir, '..')
 
  // default depth for `outdated` is 0 (cf. `ls`)
  if (npm.config.get('depth') === Infinity) npm.config.set('depth', 0)
 
  readPackageTree(dir, andRecalculateMetadata(function (er, tree) {
    if (!tree) return cb(er)
    mutateIntoLogicalTree(tree)
    outdated_(args, '', tree, {}, 0, function (er, list) {
      list = uniq(list || []).sort(function (aa, bb) {
        return aa[0].path.localeCompare(bb[0].path) ||
          aa[1].localeCompare(bb[1])
      })
      if (er || silent || list.length === 0) return cb(er, list)
      if (npm.config.get('json')) {
        output(makeJSON(list))
      } else if (npm.config.get('parseable')) {
        output(makeParseable(list))
      } else {
        var outList = list.map(makePretty)
        var outHead = [ 'Package',
                        'Current',
                        'Wanted',
                        'Latest',
                        'Location'
                      ]
        if (long) outHead.push('Package Type')
        var outTable = [outHead].concat(outList)
 
        if (npm.color) {
          outTable[0] = outTable[0].map(function (heading) {
            return styles.underline(heading)
          })
        }
 
        var tableOpts = {
          align: ['l', 'r', 'r', 'r', 'l'],
          stringLength: function (s) { return ansiTrim(s).length }
        }
        output(table(outTable, tableOpts))
      }
      process.exitCode = 1
      cb(null, list.map(function (item) { return [item[0].parent.path].concat(item.slice(1, 7)) }))
    })
  }))
}
 
// [[ dir, dep, has, want, latest, type ]]
function makePretty (p) {
  var dep = p[0]
  var depname = p[1]
  var dir = dep.path
  var has = p[2]
  var want = p[3]
  var latest = p[4]
  var type = p[6]
  var deppath = p[7]
 
  if (!npm.config.get('global')) {
    dir = path.relative(process.cwd(), dir)
  }
 
  var columns = [ depname,
                  has || 'MISSING',
                  want,
                  latest,
                  deppath
                ]
  if (long) columns[5] = type
 
  if (npm.color) {
    columns[0] = color[has === want || want === 'linked' ? 'yellow' : 'red'](columns[0]) // dep
    columns[2] = color.green(columns[2]) // want
    columns[3] = color.magenta(columns[3]) // latest
  }
 
  return columns
}
 
function makeParseable (list) {
  return list.map(function (p) {
    var dep = p[0]
    var depname = p[1]
    var dir = dep.path
    var has = p[2]
    var want = p[3]
    var latest = p[4]
    var type = p[6]
 
    var out = [
      dir,
      depname + '@' + want,
      (has ? (depname + '@' + has) : 'MISSING'),
      depname + '@' + latest
    ]
    if (long) out.push(type)
 
    return out.join(':')
  }).join(os.EOL)
}
 
function makeJSON (list) {
  var out = {}
  list.forEach(function (p) {
    var dep = p[0]
    var depname = p[1]
    var dir = dep.path
    var has = p[2]
    var want = p[3]
    var latest = p[4]
    var type = p[6]
    if (!npm.config.get('global')) {
      dir = path.relative(process.cwd(), dir)
    }
    out[depname] = { current: has,
                  wanted: want,
                  latest: latest,
                  location: dir
                }
    if (long) out[depname].type = type
  })
  return JSON.stringify(out, null, 2)
}
 
function outdated_ (args, path, tree, parentHas, depth, cb) {
  if (!tree.package) tree.package = {}
  if (path && tree.package.name) path += ' > ' + tree.package.name
  if (!path && tree.package.name) path = tree.package.name
  if (depth > npm.config.get('depth')) {
    return cb(null, [])
  }
  var types = {}
  var pkg = tree.package
 
  var deps = tree.children.filter(function (child) { return !isExtraneous(child) }) || []
 
  deps.forEach(function (dep) {
    types[moduleName(dep)] = 'dependencies'
  })
 
  Object.keys(tree.missingDeps).forEach(function (name) {
    deps.push({
      package: { name: name },
      path: tree.path,
      parent: tree,
      isMissing: true
    })
    types[name] = 'dependencies'
  })
 
  // If we explicitly asked for dev deps OR we didn't ask for production deps
  // AND we asked to save dev-deps OR we didn't ask to save anything that's NOT
  // dev deps then…
  // (All the save checking here is because this gets called from npm-update currently
  // and that requires this logic around dev deps.)
  // FIXME: Refactor npm update to not be in terms of outdated.
  var dev = npm.config.get('dev') || /^dev(elopment)?$/.test(npm.config.get('also'))
  var prod = npm.config.get('production') || /^prod(uction)?$/.test(npm.config.get('only'))
  if ((dev || !prod) &&
      (npm.config.get('save-dev') || (
        !npm.config.get('save') && !npm.config.get('save-optional')))) {
    Object.keys(tree.missingDevDeps).forEach(function (name) {
      deps.push({
        package: { name: name },
        path: tree.path,
        parent: tree,
        isMissing: true
      })
      if (!types[name]) {
        types[name] = 'devDependencies'
      }
    })
  }
 
  if (npm.config.get('save-dev')) {
    deps = deps.filter(function (dep) { return pkg.devDependencies[moduleName(dep)] })
    deps.forEach(function (dep) {
      types[moduleName(dep)] = 'devDependencies'
    })
  } else if (npm.config.get('save')) {
    // remove optional dependencies from dependencies during --save.
    deps = deps.filter(function (dep) { return !pkg.optionalDependencies[moduleName(dep)] })
  } else if (npm.config.get('save-optional')) {
    deps = deps.filter(function (dep) { return pkg.optionalDependencies[moduleName(dep)] })
    deps.forEach(function (dep) {
      types[moduleName(dep)] = 'optionalDependencies'
    })
  }
  var doUpdate = dev || (
    !prod &&
    !Object.keys(parentHas).length &&
    !npm.config.get('global')
  )
  if (doUpdate) {
    Object.keys(pkg.devDependencies).forEach(function (k) {
      if (!(k in parentHas)) {
        deps[k] = pkg.devDependencies[k]
        types[k] = 'devDependencies'
      }
    })
  }
 
  var has = Object.create(parentHas)
  tree.children.forEach(function (child) {
    if (child.package.name && child.package.private) {
      deps = deps.filter(function (dep) { return dep !== child })
    }
    has[child.package.name] = {
      version: child.package.version,
      from: child.package._from
    }
  })
 
  // now get what we should have, based on the dep.
  // if has[dep] !== shouldHave[dep], then cb with the data
  // otherwise dive into the folder
  asyncMap(deps, function (dep, cb) {
    var name = moduleName(dep)
    var required = (tree.package.dependencies)[name] ||
                   (tree.package.optionalDependencies)[name] ||
                   (tree.package.devDependencies)[name] ||
                   dep.package._requested && dep.package._requested.spec ||
                   '*'
    if (!long) return shouldUpdate(args, dep, name, has, required, depth, path, cb)
 
    shouldUpdate(args, dep, name, has, required, depth, path, cb, types[name])
  }, cb)
}
 
function shouldUpdate (args, tree, dep, has, req, depth, pkgpath, cb, type) {
  // look up the most recent version.
  // if that's what we already have, or if it's not on the args list,
  // then dive into it.  Otherwise, cb() with the data.
 
  // { version: , from: }
  var curr = has[dep]
 
  function skip (er) {
    // show user that no viable version can be found
    if (er) return cb(er)
    outdated_(args,
              pkgpath,
              tree,
              has,
              depth + 1,
              cb)
  }
 
  function doIt (wanted, latest) {
    if (!long) {
      return cb(null, [[tree, dep, curr && curr.version, wanted, latest, req, null, pkgpath]])
    }
    cb(null, [[tree, dep, curr && curr.version, wanted, latest, req, type, pkgpath]])
  }
 
  if (args.length && args.indexOf(dep) === -1) return skip()
  var parsed = npa(dep + '@' + req)
  if (tree.isLink && tree.parent && tree.parent.isTop) {
    return doIt('linked', 'linked')
  }
  if (parsed.type === 'git' || parsed.type === 'hosted') {
    return doIt('git', 'git')
  }
 
  // search for the latest package
  mapToRegistry(dep, npm.config, function (er, uri, auth) {
    if (er) return cb(er)
 
    npm.registry.get(uri, { auth: auth }, updateDeps)
  })
 
  function updateLocalDeps (latestRegistryVersion) {
    readJson(path.resolve(parsed.spec, 'package.json'), function (er, localDependency) {
      if (er) return cb()
 
      var wanted = localDependency.version
      var latest = localDependency.version
 
      if (latestRegistryVersion) {
        latest = latestRegistryVersion
        if (semver.lt(wanted, latestRegistryVersion)) {
          wanted = latestRegistryVersion
          req = dep + '@' + latest
        }
      }
 
      if (!curr || curr.version !== wanted) {
        doIt(wanted, latest)
      } else {
        skip()
      }
    })
  }
 
  function updateDeps (er, d) {
    if (er) {
      if (parsed.type !== 'local') return cb(er)
      return updateLocalDeps()
    }
 
    if (!d || !d['dist-tags'] || !d.versions) return cb()
    var l = d.versions[d['dist-tags'].latest]
    if (!l) return cb()
 
    var r = req
    if (d['dist-tags'][req]) {
      r = d['dist-tags'][req]
    }
 
    if (semver.validRange(r, true)) {
      // some kind of semver range.
      // see if it's in the doc.
      var vers = Object.keys(d.versions)
      var v = semver.maxSatisfying(vers, r, true)
      if (v) {
        return onCacheAdd(null, d.versions[v])
      }
    }
 
    // We didn't find the version in the doc.  See if cache can find it.
    cache.add(dep, req, null, false, onCacheAdd)
 
    function onCacheAdd (er, d) {
      // if this fails, then it means we can't update this thing.
      // it's probably a thing that isn't published.
      if (er) {
        if (er.code && er.code === 'ETARGET') {
          // no viable version found
          return skip(er)
        }
        return skip()
      }
 
      // check that the url origin hasn't changed (#1727) and that
      // there is no newer version available
      var dFromUrl = d._from && url.parse(d._from).protocol
      var cFromUrl = curr && curr.from && url.parse(curr.from).protocol
 
      if (!curr ||
          dFromUrl && cFromUrl && d._from !== curr.from ||
          d.version !== curr.version ||
          d.version !== l.version) {
        if (parsed.type === 'local') return updateLocalDeps(l.version)
 
        doIt(d.version, l.version)
      } else {
        skip()
      }
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/owner.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/owner.js

Statements: 8.89% (16 / 180)      Branches: 0% (0 / 114)      Functions: 0% (0 / 32)      Lines: 10.26% (16 / 156)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 2791   1 1 1 1 1 1   1           1                                                                                                                                                             1                   1                                                               1                                                       1                                                                 1                       1                                                                                                                                 1        
module.exports = owner
 
var npm = require('./npm.js')
var log = require('npmlog')
var mapToRegistry = require('./utils/map-to-registry.js')
var readLocalPkg = require('./utils/read-local-package.js')
var usage = require('./utils/usage')
var output = require('./utils/output.js')
 
owner.usage = usage(
  'owner',
  'npm owner add <user> [<@scope>/]<pkg>' +
  '\nnpm owner rm <user> [<@scope>/]<pkg>' +
  '\nnpm owner ls [<@scope>/]<pkg>'
)
owner.completion = function (opts, cb) {
  var argv = opts.conf.argv.remain
  if (argv.length > 4) return cb()
  if (argv.length <= 2) {
    var subs = ['add', 'rm']
    if (opts.partialWord === 'l') subs.push('ls')
    else subs.push('ls', 'list')
    return cb(null, subs)
  }
 
  npm.commands.whoami([], true, function (er, username) {
    if (er) return cb()
 
    var un = encodeURIComponent(username)
    var byUser, theUser
    switch (argv[2]) {
      case 'ls':
        // FIXME: there used to be registry completion here, but it stopped
        // making sense somewhere around 50,000 packages on the registry
        return cb()
 
      case 'rm':
        if (argv.length > 3) {
          theUser = encodeURIComponent(argv[3])
          byUser = '-/by-user/' + theUser + '|' + un
          return mapToRegistry(byUser, npm.config, function (er, uri, auth) {
            if (er) return cb(er)
 
            console.error(uri)
            npm.registry.get(uri, { auth: auth }, function (er, d) {
              if (er) return cb(er)
              // return the intersection
              return cb(null, d[theUser].filter(function (p) {
                // kludge for server adminery.
                return un === 'isaacs' || d[un].indexOf(p) === -1
              }))
            })
          })
        }
        // else fallthrough
        /*eslint no-fallthrough:0*/
      case 'add':
        if (argv.length > 3) {
          theUser = encodeURIComponent(argv[3])
          byUser = '-/by-user/' + theUser + '|' + un
          return mapToRegistry(byUser, npm.config, function (er, uri, auth) {
            if (er) return cb(er)
 
            console.error(uri)
            npm.registry.get(uri, { auth: auth }, function (er, d) {
              console.error(uri, er || d)
              // return mine that they're not already on.
              if (er) return cb(er)
              var mine = d[un] || []
              var theirs = d[theUser] || []
              return cb(null, mine.filter(function (p) {
                return theirs.indexOf(p) === -1
              }))
            })
          })
        }
        // just list all users who aren't me.
        return mapToRegistry('-/users', npm.config, function (er, uri, auth) {
          if (er) return cb(er)
 
          npm.registry.get(uri, { auth: auth }, function (er, list) {
            if (er) return cb()
            return cb(null, Object.keys(list).filter(function (n) {
              return n !== un
            }))
          })
        })
 
      default:
        return cb()
    }
  })
}
 
function owner (args, cb) {
  var action = args.shift()
  switch (action) {
    case 'ls': case 'list': return ls(args[0], cb)
    case 'add': return add(args[0], args[1], cb)
    case 'rm': case 'remove': return rm(args[0], args[1], cb)
    default: return unknown(action, cb)
  }
}
 
function ls (pkg, cb) {
  if (!pkg) {
    return readLocalPkg(function (er, pkg) {
      if (er) return cb(er)
      if (!pkg) return cb(owner.usage)
      ls(pkg, cb)
    })
  }
 
  mapToRegistry(pkg, npm.config, function (er, uri, auth) {
    if (er) return cb(er)
 
    npm.registry.get(uri, { auth: auth }, function (er, data) {
      var msg = ''
      if (er) {
        log.error('owner ls', "Couldn't get owner data", pkg)
        return cb(er)
      }
      var owners = data.maintainers
      if (!owners || !owners.length) {
        msg = 'admin party!'
      } else {
        msg = owners.map(function (o) {
          return o.name + ' <' + o.email + '>'
        }).join('\n')
      }
      output(msg)
      cb(er, owners)
    })
  })
}
 
function add (user, pkg, cb) {
  if (!user) return cb(owner.usage)
  if (!pkg) {
    return readLocalPkg(function (er, pkg) {
      if (er) return cb(er)
      if (!pkg) return cb(new Error(owner.usage))
      add(user, pkg, cb)
    })
  }
 
  log.verbose('owner add', '%s to %s', user, pkg)
  mutate(pkg, user, function (u, owners) {
    if (!owners) owners = []
    for (var i = 0, l = owners.length; i < l; i++) {
      var o = owners[i]
      if (o.name === u.name) {
        log.info(
          'owner add',
          'Already a package owner: ' + o.name + ' <' + o.email + '>'
        )
        return false
      }
    }
    owners.push(u)
    return owners
  }, cb)
}
 
function rm (user, pkg, cb) {
  if (!pkg) {
    return readLocalPkg(function (er, pkg) {
      if (er) return cb(er)
      if (!pkg) return cb(new Error(owner.usage))
      rm(user, pkg, cb)
    })
  }
 
  log.verbose('owner rm', '%s from %s', user, pkg)
  mutate(pkg, user, function (u, owners) {
    var found = false
    var m = owners.filter(function (o) {
      var match = (o.name === user)
      found = found || match
      return !match
    })
 
    if (!found) {
      log.info('owner rm', 'Not a package owner: ' + user)
      return false
    }
 
    if (!m.length) {
      return new Error(
        'Cannot remove all owners of a package.  Add someone else first.'
      )
    }
 
    return m
  }, cb)
}
 
function mutate (pkg, user, mutation, cb) {
  if (user) {
    var byUser = '-/user/org.couchdb.user:' + user
    mapToRegistry(byUser, npm.config, function (er, uri, auth) {
      if (er) return cb(er)
 
      npm.registry.get(uri, { auth: auth }, mutate_)
    })
  } else {
    mutate_(null, null)
  }
 
  function mutate_ (er, u) {
    if (!er && user && (!u || u.error)) {
      er = new Error(
        "Couldn't get user data for " + user + ': ' + JSON.stringify(u)
      )
    }
 
    if (er) {
      log.error('owner mutate', 'Error getting user data for %s', user)
      return cb(er)
    }
 
    if (u) u = { name: u.name, email: u.email }
    mapToRegistry(pkg, npm.config, function (er, uri, auth) {
      if (er) return cb(er)
 
      npm.registry.get(uri, { auth: auth }, function (er, data) {
        if (er) {
          log.error('owner mutate', 'Error getting package data for %s', pkg)
          return cb(er)
        }
 
        // save the number of maintainers before mutation so that we can figure
        // out if maintainers were added or removed
        var beforeMutation = data.maintainers.length
 
        var m = mutation(u, data.maintainers)
        if (!m) return cb() // handled
        if (m instanceof Error) return cb(m) // error
 
        data = {
          _id: data._id,
          _rev: data._rev,
          maintainers: m
        }
        var dataPath = pkg.replace('/', '%2f') + '/-rev/' + data._rev
        mapToRegistry(dataPath, npm.config, function (er, uri, auth) {
          if (er) return cb(er)
 
          var params = {
            method: 'PUT',
            body: data,
            auth: auth
          }
          npm.registry.request(uri, params, function (er, data) {
            if (!er && data.error) {
              er = new Error('Failed to update package metadata: ' + JSON.stringify(data))
            }
 
            if (er) {
              log.error('owner mutate', 'Failed to update package metadata')
            } else if (m.length > beforeMutation) {
              output('+ %s (%s)', user, pkg)
            } else if (m.length < beforeMutation) {
              output('- %s (%s)', user, pkg)
            }
 
            cb(er, data)
          })
        })
      })
    })
  }
}
 
function unknown (action, cb) {
  cb('Usage: \n' + owner.usage)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/pack.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/pack.js

Statements: 11.76% (6 / 51)      Branches: 0% (0 / 16)      Functions: 0% (0 / 9)      Lines: 13.64% (6 / 44)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75        2   2                             1                                 1                 1                                     1                
// npm pack <pkg>
// Packs the specified package into a .tgz file, which can then
// be installed.
 
module.exports = pack
 
var install = require('./install.js')
var cache = require('./cache.js')
var fs = require('graceful-fs')
var chain = require('slide').chain
var path = require('path')
var cwd = process.cwd()
var writeStreamAtomic = require('fs-write-stream-atomic')
var cachedPackageRoot = require('./cache/cached-package-root.js')
var output = require('./utils/output.js')
 
pack.usage = 'npm pack [[<@scope>/]<pkg>...]'
 
// if it can be installed, it can be packed.
pack.completion = install.completion
 
function pack (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
 
  if (args.length === 0) args = ['.']
 
  chain(
    args.map(function (arg) { return function (cb) { pack_(arg, cb) } }),
    function (er, files) {
      if (er || silent) return cb(er, files)
      printFiles(files, cb)
    }
  )
}
 
function printFiles (files, cb) {
  files = files.map(function (file) {
    return path.relative(cwd, file)
  })
  output(files.join('\n'))
  cb()
}
 
// add to cache, then cp to the cwd
function pack_ (pkg, cb) {
  cache.add(pkg, null, null, false, function (er, data) {
    if (er) return cb(er)
 
    // scoped packages get special treatment
    var name = data.name
    if (name[0] === '@') name = name.substr(1).replace(/\//g, '-')
    var fname = name + '-' + data.version + '.tgz'
 
    var cached = path.join(cachedPackageRoot(data), 'package.tgz')
    var from = fs.createReadStream(cached)
    var to = writeStreamAtomic(fname)
    var errState = null
 
    from.on('error', cb_)
    to.on('error', cb_)
    to.on('close', cb_)
    from.pipe(to)
 
    function cb_ (er) {
      if (errState) return
      if (er) return cb(errState = er)
      cb(null, fname)
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/ping.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/ping.js

Statements: 31.25% (5 / 16)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 35.71% (5 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 231 1   1   1   1                              
var npm = require('./npm.js')
var output = require('./utils/output.js')
 
module.exports = ping
 
ping.usage = 'npm ping\nping registry'
 
function ping (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
  var registry = npm.config.get('registry')
  if (!registry) return cb(new Error('no default registry set'))
  var auth = npm.config.getCredentialsByURI(registry)
 
  npm.registry.ping(registry, {auth: auth}, function (er, pong) {
    if (!silent) output(JSON.stringify(pong))
    cb(er, er ? null : pong)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/prefix.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/prefix.js

Statements: 45.45% (5 / 11)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 50% (5 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 171   1 1   1   1                  
module.exports = prefix
 
var npm = require('./npm.js')
var output = require('./utils/output.js')
 
prefix.usage = 'npm prefix [-g]'
 
function prefix (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
  if (!silent) output(npm.prefix)
  process.nextTick(cb.bind(this, null, npm.prefix))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/prune.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/prune.js

Statements: 28.57% (14 / 49)      Branches: 0% (0 / 10)      Functions: 0% (0 / 10)      Lines: 32.56% (14 / 43)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68    2 2   2   2 2 2 2 2                 1         1                         1             1         1     1                            
// prune extraneous packages.
 
module.exports = prune
module.exports.Pruner = Pruner
 
prune.usage = 'npm prune [[<@scope>/]<pkg>...] [--production]'
 
var npm = require('./npm.js')
var log = require('npmlog')
var util = require('util')
var moduleName = require('./utils/module-name.js')
var Installer = require('./install.js').Installer
var isExtraneous = require('./install/is-extraneous.js')
var isDev = require('./install/is-dev-dep.js')
var removeDeps = require('./install/deps.js').removeDeps
var loadExtraneous = require('./install/deps.js').loadExtraneous
var chain = require('slide').chain
 
prune.completion = require('./utils/completion/installed-deep.js')
 
function prune (args, cb) {
  var dryrun = !!npm.config.get('dry-run')
  new Pruner('.', dryrun, args).run(cb)
}
 
function Pruner (where, dryrun, args) {
  Installer.call(this, where, dryrun, args)
}
util.inherits(Pruner, Installer)
 
Pruner.prototype.loadAllDepsIntoIdealTree = function (cb) {
  log.silly('uninstall', 'loadAllDepsIntoIdealtree')
 
  var cg = this.progress.loadAllDepsIntoIdealTree
  var steps = []
 
  var self = this
  var excludeDev = npm.config.get('production') || /^prod(uction)?$/.test(npm.config.get('only'))
  function shouldPrune (child) {
    if (isExtraneous(child)) return true
    if (!excludeDev) return false
    var childName = moduleName(child)
    var isChildDev = function (parent) { return isDev(parent, childName) }
    if (child.requiredBy.every(isChildDev)) return true
  }
  function getModuleName (child) {
    // wrapping because moduleName doesn't like extra args and we're called
    // from map.
    return moduleName(child)
  }
  function matchesArg (name) {
    return self.args.length === 0 || self.args.indexOf(name) !== -1
  }
  function nameObj (name) {
    return {name: name}
  }
  var toPrune = this.currentTree.children.filter(shouldPrune).map(getModuleName).filter(matchesArg).map(nameObj)
 
  steps.push(
    [removeDeps, toPrune, this.idealTree, null, cg.newGroup('removeDeps')],
    [loadExtraneous, this.idealTree, cg.newGroup('loadExtraneous')])
  chain(steps, cb)
}
 
Pruner.prototype.runPreinstallTopLevelLifecycles = function (cb) { cb() }
Pruner.prototype.runPostinstallTopLevelLifecycles = function (cb) { cb() }
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/publish.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/publish.js

Statements: 20.69% (18 / 87)      Branches: 0% (0 / 52)      Functions: 0% (0 / 9)      Lines: 23.68% (18 / 76)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156  1   1 1 1 1 1 1 1 1 1 1 1 1 1   1       1             1                                                                                                                 1                                                                                                                                            
 
module.exports = publish
 
var npm = require('./npm.js')
var log = require('npmlog')
var path = require('path')
var readJson = require('read-package-json')
var lifecycle = require('./utils/lifecycle.js')
var chain = require('slide').chain
var mapToRegistry = require('./utils/map-to-registry.js')
var cachedPackageRoot = require('./cache/cached-package-root.js')
var createReadStream = require('graceful-fs').createReadStream
var npa = require('npm-package-arg')
var semver = require('semver')
var getPublishConfig = require('./utils/get-publish-config.js')
var output = require('./utils/output.js')
 
publish.usage = 'npm publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>]' +
                "\n\nPublishes '.' if no argument supplied" +
                '\n\nSets tag `latest` if no --tag specified'
 
publish.completion = function (opts, cb) {
  // publish can complete to a folder with a package.json
  // or a tarball, or a tarball url.
  // for now, not yet implemented.
  return cb()
}
 
function publish (args, isRetry, cb) {
  if (typeof cb !== 'function') {
    cb = isRetry
    isRetry = false
  }
  if (args.length === 0) args = ['.']
  if (args.length !== 1) return cb(publish.usage)
 
  log.verbose('publish', args)
 
  var t = npm.config.get('tag').trim()
  if (semver.validRange(t)) {
    var er = new Error('Tag name must not be a valid SemVer range: ' + t)
    return cb(er)
  }
 
  var arg = args[0]
  // if it's a local folder, then run the prepublish there, first.
  readJson(path.resolve(arg, 'package.json'), function (er, data) {
    if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
 
    if (data) {
      if (!data.name) return cb(new Error('No name provided'))
      if (!data.version) return cb(new Error('No version provided'))
    }
 
    // if readJson errors, the argument might be a tarball or package URL
    if (er) {
      npm.commands.cache.add(arg, null, null, false, function (er, data) {
        if (er) return cb(er)
        log.silly('publish', data)
        var cached = path.resolve(cachedPackageRoot(data), 'package') + '.tgz'
        // *publish* lifecycle scripts aren't run when publishing a built artifact
        // go to the next step directly
        publish_(arg, data, isRetry, cached, cb)
      })
    } else {
      var dir = arg
      npm.commands.cache.add(dir, null, null, false, function (er, data) {
        if (er) return cb(er)
        log.silly('publish', data)
        var cached = path.resolve(cachedPackageRoot(data), 'package') + '.tgz'
        // `prepublish` and `prepare` are run by cache.add
        chain(
          [
            [lifecycle, data, 'prepublishOnly', dir],
            [publish_, dir, data, isRetry, cached],
            [lifecycle, data, 'publish', dir],
            [lifecycle, data, 'postpublish', dir]
          ],
          cb
        )
      })
    }
  })
}
 
function publish_ (arg, data, isRetry, cached, cb) {
  if (!data) return cb(new Error('no package.json file found'))
 
  var mappedConfig = getPublishConfig(
    data.publishConfig,
    npm.config,
    npm.registry
  )
  var config = mappedConfig.config
  var registry = mappedConfig.client
 
  data._npmVersion = npm.version
  data._nodeVersion = process.versions.node
 
  delete data.modules
  if (data.private) {
    return cb(new Error(
      'This package has been marked as private\n' +
      "Remove the 'private' field from the package.json to publish it."
    ))
  }
 
  mapToRegistry(data.name, config, function (er, registryURI, auth, registryBase) {
    if (er) return cb(er)
 
    // we just want the base registry URL in this case
    log.verbose('publish', 'registryBase', registryBase)
    log.silly('publish', 'uploading', cached)
 
    data._npmUser = {
      name: auth.username,
      email: auth.email
    }
 
    var params = {
      metadata: data,
      body: createReadStream(cached),
      auth: auth
    }
 
    // registry-frontdoor cares about the access level, which is only
    // configurable for scoped packages
    if (config.get('access')) {
      if (!npa(data.name).scope && config.get('access') === 'restricted') {
        return cb(new Error("Can't restrict access to unscoped packages."))
      }
 
      params.access = config.get('access')
    }
 
    log.showProgress('publish:' + data._id)
    registry.publish(registryBase, params, function (er) {
      if (er && er.code === 'EPUBLISHCONFLICT' &&
          npm.config.get('force') && !isRetry) {
        log.warn('publish', 'Forced publish over ' + data._id)
        return npm.commands.unpublish([data._id], function (er) {
          // ignore errors.  Use the force.  Reach out with your feelings.
          // but if it fails again, then report the first error.
          publish([arg], er || true, cb)
        })
      }
      // report the unpublish error if this was a retry and unpublish failed
      if (er && isRetry && isRetry !== true) return cb(isRetry)
      if (er) return cb(er)
      output('+ ' + data._id)
      cb()
    })
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/rebuild.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/rebuild.js

Statements: 20.31% (13 / 64)      Branches: 0% (0 / 32)      Functions: 0% (0 / 8)      Lines: 24.53% (13 / 53)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80  1   1 1 1 1 1 1 1   1         1   1                             1                   1                                                                        
 
module.exports = rebuild
 
var readInstalled = require('read-installed')
var semver = require('semver')
var log = require('npmlog')
var npm = require('./npm.js')
var npa = require('npm-package-arg')
var usage = require('./utils/usage')
var output = require('./utils/output.js')
 
rebuild.usage = usage(
  'rebuild',
  'npm rebuild [[<@scope>/<name>]...]'
)
 
rebuild.completion = require('./utils/completion/installed-deep.js')
 
function rebuild (args, cb) {
  var opt = { depth: npm.config.get('depth'), dev: true }
  readInstalled(npm.prefix, opt, function (er, data) {
    log.info('readInstalled', typeof data)
    if (er) return cb(er)
    var set = filter(data, args)
    var folders = Object.keys(set).filter(function (f) {
      return f !== npm.prefix
    })
    if (!folders.length) return cb()
    log.silly('rebuild set', folders)
    cleanBuild(folders, set, cb)
  })
}
 
function cleanBuild (folders, set, cb) {
  npm.commands.build(folders, function (er) {
    if (er) return cb(er)
    output(folders.map(function (f) {
      return set[f] + ' ' + f
    }).join('\n'))
    cb()
  })
}
 
function filter (data, args, set, seen) {
  if (!set) set = {}
  if (!seen) seen = {}
  if (set.hasOwnProperty(data.path)) return set
  if (seen.hasOwnProperty(data.path)) return set
  seen[data.path] = true
  var pass
  if (!args.length) pass = true // rebuild everything
  else if (data.name && data._id) {
    for (var i = 0, l = args.length; i < l; i++) {
      var arg = args[i]
      var nv = npa(arg)
      var n = nv.name
      var v = nv.rawSpec
      if (n !== data.name) continue
      if (!semver.satisfies(data.version, v, true)) continue
      pass = true
      break
    }
  }
  if (pass && data._id) {
    log.verbose('rebuild', 'path, id', [data.path, data._id])
    set[data.path] = data._id
  }
  // need to also dive through kids, always.
  // since this isn't an install these won't get auto-built unless
  // they're not dependencies.
  Object.keys(data.dependencies || {}).forEach(function (d) {
    // return
    var dep = data.dependencies[d]
    if (typeof dep === 'string') return
    filter(dep, args, set, seen)
  })
  return set
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/repo.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/repo.js

Statements: 31.25% (10 / 32)      Branches: 0% (0 / 16)      Functions: 0% (0 / 5)      Lines: 34.48% (10 / 29)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 532   2   2 2 2 2 2               1               1                         1                              
module.exports = repo
 
repo.usage = 'npm repo [<pkg>]'
 
var npm = require('./npm.js')
var opener = require('opener')
var hostedGitInfo = require('hosted-git-info')
var url_ = require('url')
var fetchPackageMetadata = require('./fetch-package-metadata.js')
 
repo.completion = function (opts, cb) {
  // FIXME: there used to be registry completion here, but it stopped making
  // sense somewhere around 50,000 packages on the registry
  cb()
}
 
function repo (args, cb) {
  var n = args.length ? args[0] : '.'
  fetchPackageMetadata(n, '.', {fullMetadata: true}, function (er, d) {
    if (er) return cb(er)
    getUrlAndOpen(d, cb)
  })
}
 
function getUrlAndOpen (d, cb) {
  var r = d.repository
  if (!r) return cb(new Error('no repository'))
  // XXX remove this when npm@v1.3.10 from node 0.10 is deprecated
  // from https://github.com/npm/npm-www/issues/418
  var info = hostedGitInfo.fromUrl(r.url)
  var url = info ? info.browse() : unknownHostedUrl(r.url)
 
  if (!url) return cb(new Error('no repository: could not get url'))
 
  opener(url, { command: npm.config.get('browser') }, cb)
}
 
function unknownHostedUrl (url) {
  try {
    var idx = url.indexOf('@')
    if (idx !== -1) {
      url = url.slice(idx + 1).replace(/:([^\d]+)/, '/$1')
    }
    url = url_.parse(url)
    var protocol = url.protocol === 'https:'
                 ? 'https:'
                 : 'http:'
    return protocol + '//' + (url.host || '') +
      url.path.replace(/\.git$/, '')
  } catch (e) {}
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/restart.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/restart.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('./utils/lifecycle.js').cmd('restart')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/root.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/root.js

Statements: 45.45% (5 / 11)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 50% (5 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 171   1 1   1   1                  
module.exports = root
 
var npm = require('./npm.js')
var output = require('./utils/output.js')
 
root.usage = 'npm root [-g]'
 
function root (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
  if (!silent) output(npm.dir)
  process.nextTick(cb.bind(this, null, npm.dir))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/run-script.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/run-script.js

Statements: 12.82% (15 / 117)      Branches: 0% (0 / 88)      Functions: 0% (0 / 17)      Lines: 14.42% (15 / 104)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 1831   1 1 1 1 1 1 1 1   1         1                                                                       1                       1                                                                                                                         1                                                                                                 1                
module.exports = runScript
 
var lifecycle = require('./utils/lifecycle.js')
var npm = require('./npm.js')
var path = require('path')
var readJson = require('read-package-json')
var log = require('npmlog')
var chain = require('slide').chain
var usage = require('./utils/usage')
var output = require('./utils/output.js')
 
runScript.usage = usage(
  'run-script',
  'npm run-script <command> [-- <args>...]'
)
 
runScript.completion = function (opts, cb) {
  // see if there's already a package specified.
  var argv = opts.conf.argv.remain
 
  if (argv.length >= 4) return cb()
 
  if (argv.length === 3) {
    // either specified a script locally, in which case, done,
    // or a package, in which case, complete against its scripts
    var json = path.join(npm.localPrefix, 'package.json')
    return readJson(json, function (er, d) {
      if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
      if (er) d = {}
      var scripts = Object.keys(d.scripts || {})
      console.error('local scripts', scripts)
      if (scripts.indexOf(argv[2]) !== -1) return cb()
      // ok, try to find out which package it was, then
      var pref = npm.config.get('global') ? npm.config.get('prefix')
               : npm.localPrefix
      var pkgDir = path.resolve(pref, 'node_modules', argv[2], 'package.json')
      readJson(pkgDir, function (er, d) {
        if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
        if (er) d = {}
        var scripts = Object.keys(d.scripts || {})
        return cb(null, scripts)
      })
    })
  }
 
  readJson(path.join(npm.localPrefix, 'package.json'), function (er, d) {
    if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
    d = d || {}
    cb(null, Object.keys(d.scripts || {}))
  })
}
 
function runScript (args, cb) {
  if (!args.length) return list(cb)
 
  var pkgdir = npm.localPrefix
  var cmd = args.shift()
 
  readJson(path.resolve(pkgdir, 'package.json'), function (er, d) {
    if (er) return cb(er)
    run(d, pkgdir, cmd, args, cb)
  })
}
 
function list (cb) {
  var json = path.join(npm.localPrefix, 'package.json')
  var cmdList = [
    'publish',
    'install',
    'uninstall',
    'test',
    'stop',
    'start',
    'restart',
    'version'
  ].reduce(function (l, p) {
    return l.concat(['pre' + p, p, 'post' + p])
  }, [])
  return readJson(json, function (er, d) {
    if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
    if (er) d = {}
    var allScripts = Object.keys(d.scripts || {})
    var scripts = []
    var runScripts = []
    allScripts.forEach(function (script) {
      if (cmdList.indexOf(script) !== -1) scripts.push(script)
      else runScripts.push(script)
    })
 
    if (log.level === 'silent') {
      return cb(null, allScripts)
    }
 
    if (npm.config.get('json')) {
      output(JSON.stringify(d.scripts || {}, null, 2))
      return cb(null, allScripts)
    }
 
    if (npm.config.get('parseable')) {
      allScripts.forEach(function (script) {
        output(script + ':' + d.scripts[script])
      })
      return cb(null, allScripts)
    }
 
    var s = '\n    '
    var prefix = '  '
    if (scripts.length) {
      output('Lifecycle scripts included in %s:', d.name)
    }
    scripts.forEach(function (script) {
      output(prefix + script + s + d.scripts[script])
    })
    if (!scripts.length && runScripts.length) {
      output('Scripts available in %s via `npm run-script`:', d.name)
    } else if (runScripts.length) {
      output('\navailable via `npm run-script`:')
    }
    runScripts.forEach(function (script) {
      output(prefix + script + s + d.scripts[script])
    })
    return cb(null, allScripts)
  })
}
 
function run (pkg, wd, cmd, args, cb) {
  if (!pkg.scripts) pkg.scripts = {}
 
  var cmds
  if (cmd === 'restart' && !pkg.scripts.restart) {
    cmds = [
      'prestop', 'stop', 'poststop',
      'restart',
      'prestart', 'start', 'poststart'
    ]
  } else {
    if (!pkg.scripts[cmd]) {
      if (cmd === 'test') {
        pkg.scripts.test = 'echo \'Error: no test specified\''
      } else if (cmd === 'env') {
        if (process.platform === 'win32') {
          log.verbose('run-script using default platform env: SET (Windows)')
          pkg.scripts[cmd] = 'SET'
        } else {
          log.verbose('run-script using default platform env: env (Unix)')
          pkg.scripts[cmd] = 'env'
        }
      } else if (npm.config.get('if-present')) {
        return cb(null)
      } else {
        return cb(new Error('missing script: ' + cmd))
      }
    }
    cmds = [cmd]
  }
 
  if (!cmd.match(/^(pre|post)/)) {
    cmds = ['pre' + cmd].concat(cmds).concat('post' + cmd)
  }
 
  log.verbose('run-script', cmds)
  chain(cmds.map(function (c) {
    // pass cli arguments after -- to script.
    if (pkg.scripts[c] && c === cmd) {
      pkg.scripts[c] = pkg.scripts[c] + joinArgs(args)
    }
 
    // when running scripts explicitly, assume that they're trusted.
    return [lifecycle, pkg, c, wd, true]
  }), cb)
}
 
// join arguments after '--' and pass them to script,
// handle special characters such as ', ", ' '.
function joinArgs (args) {
  var joinedArgs = ''
  args.forEach(function (arg) {
    joinedArgs += ' "' + arg.replace(/"/g, '\\"') + '"'
  })
  return joinedArgs
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/search.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/search.js

Statements: 24.56% (14 / 57)      Branches: 0% (0 / 19)      Functions: 0% (0 / 15)      Lines: 25.93% (14 / 54)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110    1   1 1 1 1 1 1 1 1   1         1       1                                                                                                                                       1             1                        
'use strict'
 
module.exports = exports = search
 
var npm = require('./npm.js')
var allPackageSearch = require('./search/all-package-search')
var esearch = require('./search/esearch.js')
var formatPackageStream = require('./search/format-package-stream.js')
var usage = require('./utils/usage')
var output = require('./utils/output.js')
var log = require('npmlog')
var ms = require('mississippi')
 
search.usage = usage(
  'search',
  'npm search [--long] [search terms ...]'
)
 
search.completion = function (opts, cb) {
  cb(null, [])
}
 
function search (args, cb) {
  var searchOpts = {
    description: npm.config.get('description'),
    exclude: prepareExcludes(npm.config.get('searchexclude')),
    include: prepareIncludes(args, npm.config.get('searchopts')),
    limit: npm.config.get('searchlimit'),
    log: log,
    staleness: npm.config.get('searchstaleness'),
    unicode: npm.config.get('unicode')
  }
 
  if (searchOpts.include.length === 0) {
    return cb(new Error('search must be called with arguments'))
  }
 
  // Used later to figure out whether we had any packages go out
  var anyOutput = false
 
  var entriesStream = ms.through.obj()
 
  var esearchWritten = false
  esearch(searchOpts).on('data', function (pkg) {
    entriesStream.write(pkg)
    !esearchWritten && (esearchWritten = true)
  }).on('error', function (e) {
    if (esearchWritten) {
      // If esearch errored after already starting output, we can't fall back.
      return entriesStream.emit('error', e)
    }
    log.warn('search', 'fast search endpoint errored. Using old search.')
    allPackageSearch(searchOpts).on('data', function (pkg) {
      entriesStream.write(pkg)
    }).on('error', function (e) {
      entriesStream.emit('error', e)
    }).on('end', function () {
      entriesStream.end()
    })
  }).on('end', function () {
    entriesStream.end()
  })
 
  // Grab a configured output stream that will spit out packages in the
  // desired format.
  var outputStream = formatPackageStream({
    args: args, // --searchinclude options are not highlighted
    long: npm.config.get('long'),
    description: npm.config.get('description'),
    json: npm.config.get('json'),
    parseable: npm.config.get('parseable'),
    color: npm.color
  })
  outputStream.on('data', function (chunk) {
    if (!anyOutput) { anyOutput = true }
    output(chunk.toString('utf8'))
  })
 
  log.silly('search', 'searching packages')
  ms.pipe(entriesStream, outputStream, function (er) {
    if (er) return cb(er)
    if (!anyOutput && !npm.config.get('json') && !npm.config.get('parseable')) {
      output('No matches found for ' + (args.map(JSON.stringify).join(' ')))
    }
    log.silly('search', 'search completed')
    log.clearProgress()
    cb(null, {})
  })
}
 
function prepareIncludes (args, searchopts) {
  if (typeof searchopts !== 'string') searchopts = ''
  return searchopts.split(/\s+/).concat(args).map(function (s) {
    return s.toLowerCase()
  }).filter(function (s) { return s })
}
 
function prepareExcludes (searchexclude) {
  var exclude
  if (typeof searchexclude === 'string') {
    exclude = searchexclude.split(/\s+/)
  } else {
    exclude = []
  }
  return exclude.map(function (s) {
    return s.toLowerCase()
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/set.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/set.js

Statements: 62.5% (5 / 8)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 71.43% (5 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  2   2   2   2   1          
 
module.exports = set
 
set.usage = 'npm set <key> <value> (See `npm config`)'
 
var npm = require('./npm.js')
 
set.completion = npm.commands.config.completion
 
function set (args, cb) {
  if (!args.length) return cb(set.usage)
  npm.commands.config(['set'].concat(args), cb)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/shrinkwrap.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/shrinkwrap.js

Statements: 15.79% (21 / 133)      Branches: 0% (0 / 66)      Functions: 0% (0 / 23)      Lines: 17.8% (21 / 118)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200      2   2 2 2 2 2 2 2 2 2 2                         1                                       1                               1                 1                         1                                                                               1                   1                                                 1                     1                           1                            
// emit JSON describing versions of all packages currently installed (for later
// use with shrinkwrap install)
 
module.exports = exports = shrinkwrap
 
var path = require('path')
var log = require('npmlog')
var writeFileAtomic = require('write-file-atomic')
var iferr = require('iferr')
var readPackageJson = require('read-package-json')
var readPackageTree = require('read-package-tree')
var validate = require('aproba')
var chain = require('slide').chain
var npm = require('./npm.js')
var recalculateMetadata = require('./install/deps.js').recalculateMetadata
var validatePeerDeps = require('./install/deps.js').validatePeerDeps
var isExtraneous = require('./install/is-extraneous.js')
var packageId = require('./utils/package-id.js')
var moduleName = require('./utils/module-name.js')
var output = require('./utils/output.js')
var lifecycle = require('./utils/lifecycle.js')
var isDevDep = require('./install/is-dev-dep.js')
var isProdDep = require('./install/is-prod-dep.js')
var isOptDep = require('./install/is-opt-dep.js')
 
shrinkwrap.usage = 'npm shrinkwrap'
 
function shrinkwrap (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
 
  if (args.length) {
    log.warn('shrinkwrap', "doesn't take positional args")
  }
 
  var packagePath = path.join(npm.localPrefix, 'package.json')
  var prod = npm.config.get('production') || /^prod/.test(npm.config.get('only'))
 
  readPackageJson(packagePath, iferr(cb, function (pkg) {
    createShrinkwrap(npm.localPrefix, pkg, !prod, silent, cb)
  }))
}
 
module.exports.createShrinkwrap = createShrinkwrap
 
function createShrinkwrap (dir, pkg, dev, silent, cb) {
  lifecycle(pkg, 'preshrinkwrap', dir, function () {
    readPackageTree(dir, andRecalculateMetadata(iferr(cb, function (tree) {
      var pkginfo = treeToShrinkwrap(tree, dev)
 
      chain([
        [lifecycle, tree.package, 'shrinkwrap', dir],
        [shrinkwrap_, pkginfo, silent],
        [lifecycle, tree.package, 'postshrinkwrap', dir]
      ], iferr(cb, function (data) {
        cb(null, data[0])
      }))
    })))
  })
}
 
function andRecalculateMetadata (next) {
  validate('F', arguments)
  return function (er, tree) {
    validate('EO', arguments)
    if (er) return next(er)
    recalculateMetadata(tree, log, next)
  }
}
 
function treeToShrinkwrap (tree, dev) {
  validate('OB', arguments)
  var pkginfo = {}
  if (tree.package.name) pkginfo.name = tree.package.name
  if (tree.package.version) pkginfo.version = tree.package.version
  var problems = []
  if (tree.children.length) {
    shrinkwrapDeps(dev, problems, pkginfo.dependencies = {}, tree)
  }
  if (problems.length) pkginfo.problems = problems
  return pkginfo
}
 
function shrinkwrapDeps (dev, problems, deps, tree, seen) {
  validate('BAOO', [dev, problems, deps, tree])
  if (!seen) seen = {}
  if (seen[tree.path]) return
  seen[tree.path] = true
  Object.keys(tree.missingDeps).forEach(function (name) {
    var invalid = tree.children.filter(function (dep) { return moduleName(dep) === name })[0]
    if (invalid) {
      problems.push('invalid: have ' + invalid.package._id + ' (expected: ' + tree.missingDeps[name] + ') ' + invalid.path)
    } else if (!tree.package.optionalDependencies || !tree.package.optionalDependencies[name]) {
      var topname = packageId(tree)
      problems.push('missing: ' + name + '@' + tree.package.dependencies[name] +
        (topname ? ', required by ' + topname : ''))
    }
  })
  tree.children.sort(function (aa, bb) { return moduleName(aa).localeCompare(moduleName(bb)) }).forEach(function (child) {
    var childIsOnlyDev = isOnlyDev(child)
    if (!dev && childIsOnlyDev) {
      log.warn('shrinkwrap', 'Excluding devDependency: %s', child.location)
      return
    }
    var pkginfo = deps[moduleName(child)] = {}
    pkginfo.version = child.package.version
    pkginfo.from = child.package._from
    pkginfo.resolved = child.package._resolved
    if (dev && childIsOnlyDev) pkginfo.dev = true
    if (isOptional(child)) pkginfo.optional = true
    if (isExtraneous(child)) {
      problems.push('extraneous: ' + child.package._id + ' ' + child.path)
    }
    validatePeerDeps(child, function (tree, pkgname, version) {
      problems.push('peer invalid: ' + pkgname + '@' + version +
        ', required by ' + child.package._id)
    })
    if (child.children.length) {
      shrinkwrapDeps(dev, problems, pkginfo.dependencies = {}, child, seen)
    }
  })
}
 
function shrinkwrap_ (pkginfo, silent, cb) {
  if (pkginfo.problems) {
    return cb(new Error('Problems were encountered\n' +
                        'Please correct and try again.\n' +
                        pkginfo.problems.join('\n')))
  }
 
  save(pkginfo, silent, cb)
}
 
function save (pkginfo, silent, cb) {
  // copy the keys over in a well defined order
  // because javascript objects serialize arbitrarily
  var swdata
  try {
    swdata = JSON.stringify(pkginfo, null, 2) + '\n'
  } catch (er) {
    log.error('shrinkwrap', 'Error converting package info to json')
    return cb(er)
  }
 
  var file = path.resolve(npm.prefix, 'npm-shrinkwrap.json')
 
  writeFileAtomic(file, swdata, function (er) {
    if (er) return cb(er)
    if (silent) return cb(null, pkginfo)
    output('wrote npm-shrinkwrap.json')
    cb(null, pkginfo)
  })
}
 
// Returns true if the module `node` is only required direcctly as a dev
// dependency of the top level or transitively _from_ top level dev
// dependencies.
// Dual mode modules (that are both dev AND prod) should return false.
function isOnlyDev (node, seen) {
  if (!seen) seen = {}
  return node.requiredBy.length && node.requiredBy.every(andIsOnlyDev(moduleName(node), seen))
}
 
// There is a known limitation with this implementation: If a dependency is
// ONLY required by cycles that are detached from the top level then it will
// ultimately return true.
//
// This is ok though: We don't allow shrinkwraps with extraneous deps and
// these situation is caught by the extraneous checker before we get here.
function andIsOnlyDev (name, seen) {
  return function (req) {
    var isDev = isDevDep(req, name)
    var isProd = isProdDep(req, name)
    if (req.isTop) {
      return isDev && !isProd
    } else {
      if (seen[req.path]) return true
      seen[req.path] = true
      return isOnlyDev(req, seen)
    }
  }
}
 
function isOptional (node, seen) {
  if (!seen) seen = {}
  // If a node is not required by anything, then we've reached
  // the top level package.
  if (seen[node.path] || node.requiredBy.length === 0) {
    return false
  }
  seen[node.path] = true
 
  return node.requiredBy.every(function (req) {
    return isOptDep(req, node.package.name) || isOptional(req, seen)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/star.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/star.js

Statements: 35.71% (10 / 28)      Branches: 0% (0 / 12)      Functions: 0% (0 / 5)      Lines: 40% (10 / 25)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 471   1 1 1 1 1 1   1           1           1                                                  
module.exports = star
 
var npm = require('./npm.js')
var log = require('npmlog')
var asyncMap = require('slide').asyncMap
var mapToRegistry = require('./utils/map-to-registry.js')
var usage = require('./utils/usage')
var output = require('./utils/output.js')
 
star.usage = usage(
  'star',
  'npm star [<pkg>...]\n' +
  'npm unstar [<pkg>...]'
)
 
star.completion = function (opts, cb) {
  // FIXME: there used to be registry completion here, but it stopped making
  // sense somewhere around 50,000 packages on the registry
  cb()
}
 
function star (args, cb) {
  if (!args.length) return cb(star.usage)
  var s = npm.config.get('unicode') ? '\u2605 ' : '(*)'
  var u = npm.config.get('unicode') ? '\u2606 ' : '( )'
  var using = !(npm.command.match(/^un/))
  if (!using) s = u
  asyncMap(args, function (pkg, cb) {
    mapToRegistry(pkg, npm.config, function (er, uri, auth) {
      if (er) return cb(er)
 
      var params = {
        starred: using,
        auth: auth
      }
      npm.registry.star(uri, params, function (er, data, raw, req) {
        if (!er) {
          output(s + ' ' + pkg)
          log.verbose('star', data)
        }
        cb(er, data, raw, req)
      })
    })
  }, cb)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/stars.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/stars.js

Statements: 27.59% (8 / 29)      Branches: 0% (0 / 16)      Functions: 0% (0 / 5)      Lines: 30.77% (8 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 491   1   1 1 1 1   1                                                 1                            
module.exports = stars
 
stars.usage = 'npm stars [<user>]'
 
var npm = require('./npm.js')
var log = require('npmlog')
var mapToRegistry = require('./utils/map-to-registry.js')
var output = require('./utils/output.js')
 
function stars (args, cb) {
  npm.commands.whoami([], true, function (er, username) {
    var name = args.length === 1 ? args[0] : username
 
    if (er) {
      if (er.code === 'ENEEDAUTH' && !name) {
        var needAuth = new Error("'npm stars' on your own user account requires auth")
        needAuth.code = 'ENEEDAUTH'
        return cb(needAuth)
      }
 
      if (er.code !== 'ENEEDAUTH') return cb(er)
    }
 
    mapToRegistry('', npm.config, function (er, uri, auth) {
      if (er) return cb(er)
 
      var params = {
        username: name,
        auth: auth
      }
      npm.registry.stars(uri, params, showstars)
    })
  })
 
  function showstars (er, data) {
    if (er) return cb(er)
 
    if (data.rows.length === 0) {
      log.warn('stars', 'user has not starred any packages.')
    } else {
      data.rows.forEach(function (a) {
        output(a.value)
      })
    }
    cb()
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/start.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/start.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('./utils/lifecycle.js').cmd('start')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/stop.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/stop.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('./utils/lifecycle.js').cmd('stop')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/substack.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/substack.js

Statements: 45.45% (5 / 11)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 50% (5 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 241 1 1   1                     1                
module.exports = substack
var npm = require('./npm.js')
var output = require('./utils/output.js')
 
var isms = [
  '\u001b[32mbeep \u001b[35mboop\u001b[m',
  'Replace your configs with services',
  'SEPARATE ALL THE CONCERNS!',
  'MODULE ALL THE THINGS!',
  '\\o/',
  'but first, burritos',
  'full time mad scientist here',
  'c/,,\\'
]
 
function substack (args, cb) {
  var i = Math.floor(Math.random() * isms.length)
  output(isms[i])
  var c = args.shift()
  if (c) npm.commands[c](args, cb)
  else cb()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/team.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/team.js

Statements: 33.33% (8 / 24)      Branches: 0% (0 / 16)      Functions: 0% (0 / 4)      Lines: 34.78% (8 / 23)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571 1 1   1   1   1               1                                   1                                            
var mapToRegistry = require('./utils/map-to-registry.js')
var npm = require('./npm')
var output = require('./utils/output.js')
 
module.exports = team
 
team.subcommands = ['create', 'destroy', 'add', 'rm', 'ls', 'edit']
 
team.usage =
  'npm team create <scope:team>\n' +
  'npm team destroy <scope:team>\n' +
  'npm team add <scope:team> <user>\n' +
  'npm team rm <scope:team> <user>\n' +
  'npm team ls <scope>|<scope:team>\n' +
  'npm team edit <scope:team>'
 
team.completion = function (opts, cb) {
  var argv = opts.conf.argv.remain
  if (argv.length === 2) {
    return cb(null, team.subcommands)
  }
  switch (argv[2]) {
    case 'ls':
    case 'create':
    case 'destroy':
    case 'add':
    case 'rm':
    case 'edit':
      return cb(null, [])
    default:
      return cb(new Error(argv[2] + ' not recognized'))
  }
}
 
function team (args, cb) {
  // Entities are in the format <scope>:<team>
  var cmd = args.shift()
  var entity = (args.shift() || '').split(':')
  return mapToRegistry('/', npm.config, function (err, uri, auth) {
    if (err) { return cb(err) }
    try {
      return npm.registry.team(cmd, uri, {
        auth: auth,
        scope: entity[0],
        team: entity[1],
        user: args.shift()
      }, function (err, data) {
        !err && data && output(JSON.stringify(data, undefined, 2))
        cb(err, data)
      })
    } catch (e) {
      cb(e.message + '\n\nUsage:\n' + team.usage)
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/unbuild.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/unbuild.js

Statements: 29.33% (22 / 75)      Branches: 0% (0 / 36)      Functions: 0% (0 / 14)      Lines: 30.99% (22 / 71)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 1321 1 1   1 1 1 1 1 1 1 1 1 1 1       1               1   1                                                       1                             1                       1           1                               1                                                    
module.exports = unbuild
module.exports.rmStuff = rmStuff
unbuild.usage = 'npm unbuild <folder>\n(this is plumbing)'
 
var readJson = require('read-package-json')
var gentlyRm = require('./utils/gently-rm.js')
var npm = require('./npm.js')
var path = require('path')
var isInside = require('path-is-inside')
var lifecycle = require('./utils/lifecycle.js')
var asyncMap = require('slide').asyncMap
var chain = require('slide').chain
var log = require('npmlog')
var build = require('./build.js')
var output = require('./utils/output.js')
 
// args is a list of folders.
// remove any bins/etc, and then delete the folder.
function unbuild (args, silent, cb) {
  if (typeof silent === 'function') {
    cb = silent
    silent = false
  }
  asyncMap(args, unbuild_(silent), cb)
}
 
function unbuild_ (silent) {
  return function (folder, cb_) {
    function cb (er) {
      cb_(er, path.relative(npm.root, folder))
    }
    folder = path.resolve(folder)
    var base = isInside(folder, npm.prefix) ? npm.prefix : folder
    delete build._didBuild[folder]
    log.verbose('unbuild', folder.substr(npm.prefix.length + 1))
    readJson(path.resolve(folder, 'package.json'), function (er, pkg) {
      // if no json, then just trash it, but no scripts or whatever.
      if (er) return gentlyRm(folder, false, base, cb)
      chain(
        [
          [lifecycle, pkg, 'preuninstall', folder, false, true],
          [lifecycle, pkg, 'uninstall', folder, false, true],
          !silent && function (cb) {
            output('unbuild ' + pkg._id)
            cb()
          },
          [rmStuff, pkg, folder],
          [lifecycle, pkg, 'postuninstall', folder, false, true],
          [gentlyRm, folder, false, base]
        ],
        cb
      )
    })
  }
}
 
function rmStuff (pkg, folder, cb) {
  // if it's global, and folder is in {prefix}/node_modules,
  // then bins are in {prefix}/bin
  // otherwise, then bins are in folder/../.bin
  var parent = pkg.name[0] === '@' ? path.dirname(path.dirname(folder)) : path.dirname(folder)
  var gnm = npm.dir
  var top = gnm === parent
 
  log.verbose('unbuild rmStuff', pkg._id, 'from', gnm)
  if (!top) log.verbose('unbuild rmStuff', 'in', parent)
  asyncMap([rmBins, rmMans], function (fn, cb) {
    fn(pkg, folder, parent, top, cb)
  }, cb)
}
 
function rmBins (pkg, folder, parent, top, cb) {
  if (!pkg.bin) return cb()
  var binRoot = top ? npm.bin : path.resolve(parent, '.bin')
  asyncMap(Object.keys(pkg.bin), function (b, cb) {
    if (process.platform === 'win32') {
      chain([ [gentlyRm, path.resolve(binRoot, b) + '.cmd', true, folder],
              [gentlyRm, path.resolve(binRoot, b), true, folder] ], cb)
    } else {
      gentlyRm(path.resolve(binRoot, b), true, folder, cb)
    }
  }, gentlyRmBinRoot)
 
  function gentlyRmBinRoot (err) {
    if (err || top) return cb(err)
    return gentlyRm(binRoot, true, parent, cb)
  }
}
 
function rmMans (pkg, folder, parent, top, cb) {
  if (!pkg.man ||
      !top ||
      process.platform === 'win32' ||
      !npm.config.get('global')) {
    return cb()
  }
  var manRoot = path.resolve(npm.config.get('prefix'), 'share', 'man')
  log.verbose('rmMans', 'man files are', pkg.man, 'in', manRoot)
  asyncMap(pkg.man, function (man, cb) {
    if (Array.isArray(man)) {
      man.forEach(rmMan)
    } else {
      rmMan(man)
    }
 
    function rmMan (man) {
      log.silly('rmMan', 'preparing to remove', man)
      var parseMan = man.match(/(.*\.([0-9]+)(\.gz)?)$/)
      if (!parseMan) {
        log.error(
          'rmMan', man, 'is not a valid name for a man file.',
          'Man files must end with a number, ' +
          'and optionally a .gz suffix if they are compressed.'
        )
        return cb()
      }
 
      var stem = parseMan[1]
      var sxn = parseMan[2]
      var gz = parseMan[3] || ''
      var bn = path.basename(stem)
      var manDest = path.join(
        manRoot,
        'man' + sxn,
        (bn.indexOf(pkg.name) === 0 ? bn : pkg.name + '-' + bn) + '.' + sxn + gz
      )
      gentlyRm(manDest, true, cb)
    }
  }, cb)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/uninstall.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/uninstall.js

Statements: 21.15% (11 / 52)      Branches: 0% (0 / 17)      Functions: 0% (0 / 9)      Lines: 23.91% (11 / 46)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81      2 2   2 2 2 2 2 2 2                           1                                                   1                                                        
'use strict'
// remove a package.
 
module.exports = uninstall
module.exports.Uninstaller = Uninstaller
 
var util = require('util')
var path = require('path')
var validate = require('aproba')
var chain = require('slide').chain
var readJson = require('read-package-json')
var npm = require('./npm.js')
var Installer = require('./install.js').Installer
var getSaveType = require('./install/save.js').getSaveType
var removeDeps = require('./install/deps.js').removeDeps
var loadExtraneous = require('./install/deps.js').loadExtraneous
var log = require('npmlog')
var usage = require('./utils/usage')
 
uninstall.usage = usage(
  'uninstall',
  'npm uninstall [<@scope>/]<pkg>[@<version>]... [--save|--save-dev|--save-optional]'
)
 
uninstall.completion = require('./utils/completion/installed-shallow.js')
 
function uninstall (args, cb) {
  validate('AF', arguments)
  // the /path/to/node_modules/..
  var dryrun = !!npm.config.get('dry-run')
 
  if (args.length === 1 && args[0] === '.') args = []
  args = args.filter(function (a) {
    return path.resolve(a) !== where
  })
 
  var where = npm.config.get('global') || !args.length
            ? path.resolve(npm.globalDir, '..')
            : npm.prefix
 
  if (args.length) {
    new Uninstaller(where, dryrun, args).run(cb)
  } else {
    // remove this package from the global space, if it's installed there
    readJson(path.resolve(npm.localPrefix, 'package.json'), function (er, pkg) {
      if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
      if (er) return cb(uninstall.usage)
      new Uninstaller(where, dryrun, [pkg.name]).run(cb)
    })
  }
}
 
function Uninstaller (where, dryrun, args) {
  validate('SBA', arguments)
  Installer.call(this, where, dryrun, args)
}
util.inherits(Uninstaller, Installer)
 
Uninstaller.prototype.loadArgMetadata = function (next) {
  this.args = this.args.map(function (arg) { return {name: arg} })
  next()
}
 
Uninstaller.prototype.loadAllDepsIntoIdealTree = function (cb) {
  validate('F', arguments)
  log.silly('uninstall', 'loadAllDepsIntoIdealtree')
  var saveDeps = getSaveType(this.args)
 
  var cg = this.progress.loadAllDepsIntoIdealTree
  var steps = []
 
  steps.push(
    [removeDeps, this.args, this.idealTree, saveDeps, cg.newGroup('removeDeps')],
    [loadExtraneous, this.idealTree, cg.newGroup('loadExtraneous')])
  chain(steps, cb)
}
 
Uninstaller.prototype.runPreinstallTopLevelLifecycles = function (cb) { cb() }
Uninstaller.prototype.runPostinstallTopLevelLifecycles = function (cb) { cb() }
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/unpublish.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/unpublish.js

Statements: 16.67% (14 / 84)      Branches: 0% (0 / 49)      Functions: 0% (0 / 14)      Lines: 20% (14 / 70)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120  1   1 1 1 1 1 1 1 1   1   1                                                                             1                                                             1           1                                                          
 
module.exports = unpublish
 
var log = require('npmlog')
var npm = require('./npm.js')
var readJson = require('read-package-json')
var path = require('path')
var mapToRegistry = require('./utils/map-to-registry.js')
var npa = require('npm-package-arg')
var getPublishConfig = require('./utils/get-publish-config.js')
var output = require('./utils/output.js')
 
unpublish.usage = 'npm unpublish [<@scope>/]<pkg>[@<version>]'
 
unpublish.completion = function (opts, cb) {
  if (opts.conf.argv.remain.length >= 3) return cb()
  npm.commands.whoami([], true, function (er, username) {
    if (er) return cb()
 
    var un = encodeURIComponent(username)
    if (!un) return cb()
    var byUser = '-/by-user/' + un
    mapToRegistry(byUser, npm.config, function (er, uri, auth) {
      if (er) return cb(er)
 
      npm.registry.get(uri, { auth: auth }, function (er, pkgs) {
        // do a bit of filtering at this point, so that we don't need
        // to fetch versions for more than one thing, but also don't
        // accidentally a whole project.
        pkgs = pkgs[un]
        if (!pkgs || !pkgs.length) return cb()
        var pp = npa(opts.partialWord).name
        pkgs = pkgs.filter(function (p) {
          return p.indexOf(pp) === 0
        })
        if (pkgs.length > 1) return cb(null, pkgs)
        mapToRegistry(pkgs[0], npm.config, function (er, uri, auth) {
          if (er) return cb(er)
 
          npm.registry.get(uri, { auth: auth }, function (er, d) {
            if (er) return cb(er)
            var vers = Object.keys(d.versions)
            if (!vers.length) return cb(null, pkgs)
            return cb(null, vers.map(function (v) {
              return pkgs[0] + '@' + v
            }))
          })
        })
      })
    })
  })
}
 
function unpublish (args, cb) {
  if (args.length > 1) return cb(unpublish.usage)
 
  var thing = args.length ? npa(args[0]) : {}
  var project = thing.name
  var version = thing.rawSpec
 
  log.silly('unpublish', 'args[0]', args[0])
  log.silly('unpublish', 'thing', thing)
  if (!version && !npm.config.get('force')) {
    return cb(
      'Refusing to delete entire project.\n' +
      'Run with --force to do this.\n' +
      unpublish.usage
    )
  }
 
  if (!project || path.resolve(project) === npm.localPrefix) {
    // if there's a package.json in the current folder, then
    // read the package name and version out of that.
    var cwdJson = path.join(npm.localPrefix, 'package.json')
    return readJson(cwdJson, function (er, data) {
      if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
      if (er) return cb('Usage:\n' + unpublish.usage)
      log.verbose('unpublish', data)
      gotProject(data.name, data.version, data.publishConfig, cb)
    })
  }
  return gotProject(project, version, cb)
}
 
function gotProject (project, version, publishConfig, cb_) {
  if (typeof cb_ !== 'function') {
    cb_ = publishConfig
    publishConfig = null
  }
 
  function cb (er) {
    if (er) return cb_(er)
    output('- ' + project + (version ? '@' + version : ''))
    cb_()
  }
 
  var mappedConfig = getPublishConfig(publishConfig, npm.config, npm.registry)
  var config = mappedConfig.config
  var registry = mappedConfig.client
 
  // remove from the cache first
  npm.commands.cache(['clean', project, version], function (er) {
    if (er) {
      log.error('unpublish', 'Failed to clean cache')
      return cb(er)
    }
 
    mapToRegistry(project, config, function (er, uri, auth) {
      if (er) return cb(er)
 
      var params = {
        version: version,
        auth: auth
      }
      registry.unpublish(uri, params, cb)
    })
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/update.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/update.js

Statements: 20% (7 / 35)      Branches: 0% (0 / 19)      Functions: 0% (0 / 6)      Lines: 22.58% (7 / 31)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 662   2 2 2 2 2                   1                                                                                                  
module.exports = update
 
var url = require('url')
var log = require('npmlog')
var chain = require('slide').chain
var npm = require('./npm.js')
var Installer = require('./install.js').Installer
var usage = require('./utils/usage')
 
update.usage = usage(
  'update',
  'npm update [-g] [<pkg>...]'
)
 
update.completion = npm.commands.outdated.completion
 
function update (args, cb) {
  var dryrun = false
  if (npm.config.get('dry-run')) dryrun = true
 
  npm.commands.outdated(args, true, function (er, rawOutdated) {
    if (er) return cb(er)
    var outdated = rawOutdated.map(function (ww) {
      return {
        dep: ww[0],
        depname: ww[1],
        current: ww[2],
        wanted: ww[3],
        latest: ww[4],
        req: ww[5],
        what: ww[1] + '@' + ww[3]
      }
    })
 
    var wanted = outdated.filter(function (ww) {
      if (ww.current === ww.wanted && ww.wanted !== ww.latest) {
        log.verbose(
          'outdated',
          'not updating', ww.depname,
          "because it's currently at the maximum version that matches its specified semver range"
        )
      }
      return ww.current !== ww.wanted && ww.latest !== 'linked'
    })
    if (wanted.length === 0) return cb()
 
    log.info('outdated', 'updating', wanted)
    var toInstall = {}
    wanted.forEach(function (ww) {
      // use the initial installation method (repo, tar, git) for updating
      if (url.parse(ww.req).protocol) ww.what = ww.req
 
      var where = ww.dep.parent && ww.dep.parent.path || ww.dep.path
      if (toInstall[where]) {
        toInstall[where].push(ww.what)
      } else {
        toInstall[where] = [ww.what]
      }
    })
    chain(Object.keys(toInstall).map(function (where) {
      return [new Installer(where, dryrun, toInstall[where]), 'run']
    }), cb)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/version.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/version.js

Statements: 16.28% (28 / 172)      Branches: 0% (0 / 87)      Functions: 0% (0 / 32)      Lines: 18.42% (28 / 152)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291    2   2 2 2 2 2 2 2 2                           1                                                   1                               1                                   1                                           1                             1 1                       1               1                                             1                             1       1               1                   1 1         1                             1                                                               1                                           1                        
// npm version <newver>
 
module.exports = version
 
var semver = require('semver')
var path = require('path')
var fs = require('graceful-fs')
var writeFileAtomic = require('write-file-atomic')
var chain = require('slide').chain
var log = require('npmlog')
var npm = require('./npm.js')
var git = require('./utils/git.js')
var assert = require('assert')
var lifecycle = require('./utils/lifecycle.js')
var parseJSON = require('./utils/parse-json.js')
var output = require('./utils/output.js')
 
version.usage = 'npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git]' +
                '\n(run in package dir)\n' +
                "'npm -v' or 'npm --version' to print npm version " +
                '(' + npm.version + ')\n' +
                "'npm view <pkg> version' to view a package's " +
                'published version\n' +
                "'npm ls' to inspect current package/dependency versions"
 
function version (args, silent, cb_) {
  if (typeof cb_ !== 'function') {
    cb_ = silent
    silent = false
  }
  if (args.length > 1) return cb_(version.usage)
 
  readPackage(function (er, data) {
    if (!args.length) return dump(data, cb_)
 
    if (er) {
      log.error('version', 'No valid package.json found')
      return cb_(er)
    }
 
    if (args[0] === 'from-git') {
      retrieveTagVersion(silent, data, cb_)
    } else {
      var newVersion = semver.valid(args[0])
      if (!newVersion) newVersion = semver.inc(data.version, args[0])
      if (!newVersion) return cb_(version.usage)
      persistVersion(newVersion, silent, data, cb_)
    }
  })
}
 
function retrieveTagVersion (silent, data, cb_) {
  chain([
    verifyGit,
    parseLastGitTag
  ], function (er, results) {
    if (er) return cb_(er)
    var localData = {
      hasGit: true,
      existingTag: true
    }
 
    var version = results[results.length - 1]
    persistVersion(version, silent, data, localData, cb_)
  })
}
 
function parseLastGitTag (cb) {
  var options = { env: process.env }
  git.whichAndExec(['describe', '--abbrev=0'], options, function (er, stdout) {
    if (er) {
      if (er.message.indexOf('No names found') !== -1) return cb(new Error('No tags found'))
      return cb(er)
    }
 
    var tag = stdout.trim()
    var prefix = npm.config.get('tag-version-prefix')
    // Strip the prefix from the start of the tag:
    if (tag.indexOf(prefix) === 0) tag = tag.slice(prefix.length)
    var version = semver.valid(tag)
    if (!version) return cb(new Error(tag + ' is not a valid version'))
    cb(null, version)
  })
}
 
function persistVersion (newVersion, silent, data, localData, cb_) {
  if (typeof localData === 'function') {
    cb_ = localData
    localData = {}
  }
 
  if (data.version === newVersion) return cb_(new Error('Version not changed'))
  data.version = newVersion
  var lifecycleData = Object.create(data)
  lifecycleData._id = data.name + '@' + newVersion
 
  var where = npm.prefix
  chain([
    !localData.hasGit && [checkGit, localData],
    [lifecycle, lifecycleData, 'preversion', where],
    [updatePackage, newVersion, silent],
    [lifecycle, lifecycleData, 'version', where],
    [commit, localData, newVersion],
    [lifecycle, lifecycleData, 'postversion', where]
  ], cb_)
}
 
function readPackage (cb) {
  var packagePath = path.join(npm.localPrefix, 'package.json')
  fs.readFile(packagePath, function (er, data) {
    if (er) return cb(new Error(er))
    if (data) data = data.toString()
    try {
      data = JSON.parse(data)
    } catch (e) {
      er = e
      data = null
    }
    cb(er, data)
  })
}
 
function updatePackage (newVersion, silent, cb_) {
  function cb (er) {
    if (!er && !silent) output('v' + newVersion)
    cb_(er)
  }
 
  readPackage(function (er, data) {
    if (er) return cb(new Error(er))
    data.version = newVersion
    write(data, 'package.json', cb)
  })
}
 
function commit (localData, newVersion, cb) {
  updateShrinkwrap(newVersion, function (er, hasShrinkwrap) {
    if (er || !localData.hasGit) return cb(er)
    localData.hasShrinkwrap = hasShrinkwrap
    _commit(newVersion, localData, cb)
  })
}
 
function updateShrinkwrap (newVersion, cb) {
  fs.readFile(path.join(npm.localPrefix, 'npm-shrinkwrap.json'), function (er, data) {
    if (er && er.code === 'ENOENT') return cb(null, false)
 
    try {
      data = data.toString()
      data = parseJSON(data)
    } catch (er) {
      log.error('version', 'Bad npm-shrinkwrap.json data')
      return cb(er)
    }
 
    data.version = newVersion
    write(data, 'npm-shrinkwrap.json', function (er) {
      if (er) {
        log.error('version', 'Bad npm-shrinkwrap.json data')
        return cb(er)
      }
      cb(null, true)
    })
  })
}
 
function dump (data, cb) {
  var v = {}
 
  if (data && data.name && data.version) v[data.name] = data.version
  v.npm = npm.version
  Object.keys(process.versions).sort().forEach(function (k) {
    v[k] = process.versions[k]
  })
 
  if (npm.config.get('json')) v = JSON.stringify(v, null, 2)
 
  output(v)
  cb()
}
 
function statGitFolder (cb) {
  fs.stat(path.join(npm.localPrefix, '.git'), cb)
}
 
function callGitStatus (cb) {
  git.whichAndExec(
    [ 'status', '--porcelain' ],
    { env: process.env },
    cb
  )
}
 
function cleanStatusLines (stdout) {
  var lines = stdout.trim().split('\n').filter(function (line) {
    return line.trim() && !line.match(/^\?\? /)
  }).map(function (line) {
    return line.trim()
  })
 
  return lines
}
 
function verifyGit (cb) {
  function checkStatus (er) {
    if (er) return cb(er)
    callGitStatus(checkStdout)
  }
 
  function checkStdout (er, stdout) {
    if (er) return cb(er)
    var lines = cleanStatusLines(stdout)
    if (lines.length > 0) {
      return cb(new Error(
        'Git working directory not clean.\n' + lines.join('\n')
      ))
    }
 
    cb()
  }
 
  statGitFolder(checkStatus)
}
 
function checkGit (localData, cb) {
  statGitFolder(function (er) {
    var doGit = !er && npm.config.get('git-tag-version')
    if (!doGit) {
      if (er) log.verbose('version', 'error checking for .git', er)
      log.verbose('version', 'not tagging in git')
      return cb(null, false)
    }
 
    // check for git
    callGitStatus(function (er, stdout) {
      if (er && er.code === 'ENOGIT') {
        log.warn(
          'version',
          'This is a Git checkout, but the git command was not found.',
          'npm could not create a Git tag for this release!'
        )
        return cb(null, false)
      }
 
      var lines = cleanStatusLines(stdout)
      if (lines.length && !npm.config.get('force')) {
        return cb(new Error(
          'Git working directory not clean.\n' + lines.join('\n')
        ))
      }
      localData.hasGit = true
      cb(null, true)
    })
  })
}
 
function _commit (version, localData, cb) {
  var packagePath = path.join(npm.localPrefix, 'package.json')
  var options = { env: process.env }
  var message = npm.config.get('message').replace(/%s/g, version)
  var sign = npm.config.get('sign-git-tag')
  var flag = sign ? '-sm' : '-am'
  chain(
    [
      git.chainableExec([ 'add', packagePath ], options),
      localData.hasShrinkwrap && git.chainableExec([ 'add', path.join(npm.localPrefix, 'npm-shrinkwrap.json') ], options),
      git.chainableExec([ 'commit', '-m', message ], options),
      !localData.existingTag && git.chainableExec([
        'tag',
        npm.config.get('tag-version-prefix') + version,
        flag,
        message
      ], options)
    ],
    cb
  )
}
 
function write (data, file, cb) {
  assert(data && typeof data === 'object', 'must pass data to version write')
  assert(typeof file === 'string', 'must pass filename to write to version write')
 
  log.verbose('version.write', 'data', data, 'to', file)
  writeFileAtomic(
    path.join(npm.localPrefix, file),
    new Buffer(JSON.stringify(data, null, 2) + '\n'),
    cb
  )
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/view.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/view.js

Statements: 9.48% (22 / 232)      Branches: 0% (0 / 184)      Functions: 0% (0 / 30)      Lines: 10.58% (22 / 208)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336  1   1 1 1 1 1 1 1 1 1   1         1                                         1                                           1                                                                         1                                                                                                                     1               1                           1                   1                                                                                                       1                                                                                                                       1                                                     1              
// npm view [pkg [pkg ...]]
module.exports = view
 
var npm = require('./npm.js')
var readJson = require('read-package-json')
var log = require('npmlog')
var util = require('util')
var semver = require('semver')
var mapToRegistry = require('./utils/map-to-registry.js')
var npa = require('npm-package-arg')
var path = require('path')
var usage = require('./utils/usage')
 
view.usage = usage(
  'view',
  'npm view [<@scope>/]<pkg>[@<version>] [<field>[.subfield]...]'
)
 
view.completion = function (opts, cb) {
  if (opts.conf.argv.remain.length <= 2) {
    // FIXME: there used to be registry completion here, but it stopped making
    // sense somewhere around 50,000 packages on the registry
    return cb()
  }
  // have the package, get the fields.
  var tag = npm.config.get('tag')
  mapToRegistry(opts.conf.argv.remain[2], npm.config, function (er, uri, auth) {
    if (er) return cb(er)
 
    npm.registry.get(uri, { auth: auth }, function (er, d) {
      if (er) return cb(er)
      var dv = d.versions[d['dist-tags'][tag]]
      var fields = []
      d.versions = Object.keys(d.versions).sort(semver.compareLoose)
      fields = getFields(d).concat(getFields(dv))
      cb(null, fields)
    })
  })
 
  function getFields (d, f, pref) {
    f = f || []
    if (!d) return f
    pref = pref || []
    Object.keys(d).forEach(function (k) {
      if (k.charAt(0) === '_' || k.indexOf('.') !== -1) return
      var p = pref.concat(k).join('.')
      f.push(p)
      if (Array.isArray(d[k])) {
        d[k].forEach(function (val, i) {
          var pi = p + '[' + i + ']'
          if (val && typeof val === 'object') getFields(val, f, [p])
          else f.push(pi)
        })
        return
      }
      if (typeof d[k] === 'object') getFields(d[k], f, [p])
    })
    return f
  }
}
 
function view (args, silent, cb) {
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
 
  if (!args.length) args = ['.']
 
  var pkg = args.shift()
  var nv = npa(pkg)
  var name = nv.name
  var local = (name === '.' || !name)
 
  if (npm.config.get('global') && local) {
    return cb(new Error('Cannot use view command in global mode.'))
  }
 
  if (local) {
    var dir = npm.prefix
    readJson(path.resolve(dir, 'package.json'), function (er, d) {
      d = d || {}
      if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
      if (!d.name) return cb(new Error('Invalid package.json'))
 
      var p = d.name
      nv = npa(p)
      if (pkg && ~pkg.indexOf('@')) {
        nv.rawSpec = pkg.split('@')[pkg.indexOf('@')]
      }
 
      fetchAndRead(nv, args, silent, cb)
    })
  } else {
    fetchAndRead(nv, args, silent, cb)
  }
}
 
function fetchAndRead (nv, args, silent, cb) {
  // get the data about this package
  var name = nv.name
  var version = nv.rawSpec || npm.config.get('tag')
 
  mapToRegistry(name, npm.config, function (er, uri, auth) {
    if (er) return cb(er)
 
    npm.registry.get(uri, { auth: auth }, function (er, data) {
      if (er) return cb(er)
      if (data['dist-tags'] && data['dist-tags'].hasOwnProperty(version)) {
        version = data['dist-tags'][version]
      }
 
      if (data.time && data.time.unpublished) {
        var u = data.time.unpublished
        er = new Error('Unpublished by ' + u.name + ' on ' + u.time)
        er.statusCode = 404
        er.code = 'E404'
        er.pkgid = data._id
        return cb(er, data)
      }
 
      var results = []
      var error = null
      var versions = data.versions || {}
      data.versions = Object.keys(versions).sort(semver.compareLoose)
      if (!args.length) args = ['']
 
      // remove readme unless we asked for it
      if (args.indexOf('readme') === -1) {
        delete data.readme
      }
 
      Object.keys(versions).forEach(function (v) {
        if (semver.satisfies(v, version, true)) {
          args.forEach(function (args) {
            // remove readme unless we asked for it
            if (args.indexOf('readme') !== -1) {
              delete versions[v].readme
            }
            results.push(showFields(data, versions[v], args))
          })
        }
      })
      results = results.reduce(reducer, {})
      var retval = results
 
      if (args.length === 1 && args[0] === '') {
        retval = cleanBlanks(retval)
        log.silly('cleanup', retval)
      }
 
      if (error || silent) cb(error, retval)
      else printData(results, data._id, cb.bind(null, error, retval))
    })
  })
}
 
function cleanBlanks (obj) {
  var clean = {}
  Object.keys(obj).forEach(function (version) {
    clean[version] = obj[version]['']
  })
  return clean
}
 
function reducer (l, r) {
  if (r) {
    Object.keys(r).forEach(function (v) {
      l[v] = l[v] || {}
      Object.keys(r[v]).forEach(function (t) {
        l[v][t] = r[v][t]
      })
    })
  }
 
  return l
}
 
// return whatever was printed
function showFields (data, version, fields) {
  var o = {}
  ;[data, version].forEach(function (s) {
    Object.keys(s).forEach(function (k) {
      o[k] = s[k]
    })
  })
  return search(o, fields.split('.'), version.version, fields)
}
 
function search (data, fields, version, title) {
  var field
  var tail = fields
  while (!field && fields.length) field = tail.shift()
  fields = [field].concat(tail)
  var o
  if (!field && !tail.length) {
    o = {}
    o[version] = {}
    o[version][title] = data
    return o
  }
  var index = field.match(/(.+)\[([^\]]+)\]$/)
  if (index) {
    field = index[1]
    index = index[2]
    if (data.field && data.field.hasOwnProperty(index)) {
      return search(data[field][index], tail, version, title)
    } else {
      field = field + '[' + index + ']'
    }
  }
  if (Array.isArray(data)) {
    if (data.length === 1) {
      return search(data[0], fields, version, title)
    }
    var results = []
    data.forEach(function (data, i) {
      var tl = title.length
      var newt = title.substr(0, tl - fields.join('.').length - 1) +
                 '[' + i + ']' + [''].concat(fields).join('.')
      results.push(search(data, fields.slice(), version, newt))
    })
    results = results.reduce(reducer, {})
    return results
  }
  if (!data.hasOwnProperty(field)) return undefined
  data = data[field]
  if (tail.length) {
    if (typeof data === 'object') {
      // there are more fields to deal with.
      return search(data, tail, version, title)
    } else {
      return new Error('Not an object: ' + data)
    }
  }
  o = {}
  o[version] = {}
  o[version][title] = data
  return o
}
 
function printData (data, name, cb) {
  var versions = Object.keys(data)
  var msg = ''
  var msgJson = []
  var includeVersions = versions.length > 1
  var includeFields
 
  versions.forEach(function (v) {
    var fields = Object.keys(data[v])
    includeFields = includeFields || (fields.length > 1)
    if (npm.config.get('json')) msgJson.push({})
    fields.forEach(function (f) {
      var d = cleanup(data[v][f])
      if (fields.length === 1 && npm.config.get('json')) {
        msgJson[msgJson.length - 1][f] = d
      }
      if (includeVersions || includeFields || typeof d !== 'string') {
        if (npm.config.get('json')) {
          msgJson[msgJson.length - 1][f] = d
        } else {
          d = util.inspect(d, false, 5, npm.color)
        }
      } else if (typeof d === 'string' && npm.config.get('json')) {
        d = JSON.stringify(d)
      }
      if (!npm.config.get('json')) {
        if (f && includeFields) f += ' = '
        if (d.indexOf('\n') !== -1) d = ' \n' + d
        msg += (includeVersions ? name + '@' + v + ' ' : '') +
               (includeFields ? f : '') + d + '\n'
      }
    })
  })
 
  if (npm.config.get('json')) {
    if (msgJson.length && Object.keys(msgJson[0]).length === 1) {
      var k = Object.keys(msgJson[0])[0]
      msgJson = msgJson.map(function (m) { return m[k] })
    }
 
    if (msgJson.length === 1) {
      msg = JSON.stringify(msgJson[0], null, 2) + '\n'
    } else if (msgJson.length > 1) {
      msg = JSON.stringify(msgJson, null, 2) + '\n'
    }
  }
 
  // preserve output symmetry by adding a whitespace-only line at the end if
  // there's one at the beginning
  if (/^\s*\n/.test(msg)) msg += '\n'
 
  // disable the progress bar entirely, as we can't meaningfully update it if
  // we may have partial lines printed.
  log.disableProgress()
 
  // print directly to stdout to not unnecessarily add blank lines
  process.stdout.write(msg)
 
  cb(null, data)
}
function cleanup (data) {
  if (Array.isArray(data)) {
    return data.map(cleanup)
  }
  if (!data || typeof data !== 'object') return data
 
  if (typeof data.versions === 'object' &&
      data.versions &&
      !Array.isArray(data.versions)) {
    data.versions = Object.keys(data.versions || {})
  }
 
  var keys = Object.keys(data)
  keys.forEach(function (d) {
    if (d.charAt(0) === '_') delete data[d]
    else if (typeof data[d] === 'object') data[d] = cleanup(data[d])
  })
  keys = Object.keys(data)
  if (keys.length <= 3 &&
      data.name &&
      (keys.length === 1 ||
       keys.length === 3 && data.email && data.url ||
       keys.length === 2 && (data.email || data.url))) {
    data = unparsePerson(data)
  }
  return data
}
function unparsePerson (d) {
  if (typeof d === 'string') return d
  return d.name +
    (d.email ? ' <' + d.email + '>' : '') +
    (d.url ? ' (' + d.url + ')' : '')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/visnup.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/visnup.js

Statements: 41.67% (5 / 12)      Branches: 0% (0 / 4)      Functions: 0% (0 / 3)      Lines: 45.45% (5 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 451 1 1   1                                                       1                        
module.exports = visnup
var npm = require('./npm.js')
var output = require('./utils/output.js')
 
var handsomeFace = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 237, 236, 236, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 235, 236, 235, 233, 237, 235, 233, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 235, 233, 232, 235, 235, 234, 233, 236, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 237, 235, 232, 232, 234, 233, 233, 232, 232, 233, 232, 232, 235, 232, 233, 234, 234, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 232, 232, 232, 239, 238, 235, 233, 232, 232, 232, 232, 232, 232, 232, 233, 235, 232, 233, 233, 232, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 234, 234, 232, 233, 234, 233, 234, 235, 233, 235, 60, 238, 238, 234, 234, 233, 234, 233, 238, 251, 246, 233, 233, 232, 0, 0, 0, 0, 0, 0],
  [0, 0, 233, 233, 233, 232, 232, 239, 249, 251, 252, 231, 231, 188, 250, 254, 59, 60, 255, 231, 231, 231, 252, 235, 239, 235, 232, 233, 0, 0, 0, 0, 0, 0],
  [0, 0, 232, 233, 232, 232, 232, 248, 231, 231, 231, 231, 231, 231, 231, 254, 238, 254, 231, 231, 231, 231, 231, 252, 233, 235, 237, 233, 234, 0, 0, 0, 0, 0],
  [0, 0, 233, 232, 232, 232, 248, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 251, 233, 233, 233, 236, 233, 0, 0, 0, 0],
  [232, 233, 233, 232, 232, 246, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 249, 233, 234, 234, 0, 0, 0, 0],
  [232, 232, 232, 232, 233, 249, 231, 255, 255, 255, 255, 254, 109, 60, 239, 237, 238, 237, 235, 235, 235, 235, 236, 235, 235, 235, 234, 232, 232, 232, 232, 232, 233, 0],
  [0, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 233, 235, 236, 238, 238, 235, 188, 254, 254, 145, 236, 252, 254, 254, 254, 254, 249, 236, 235, 232, 232, 233, 0],
  [0, 0, 233, 237, 249, 239, 233, 252, 231, 231, 231, 231, 231, 231, 254, 235, 235, 254, 231, 231, 251, 235, 237, 231, 231, 231, 231, 7, 237, 235, 232, 233, 233, 0],
  [0, 0, 0, 0, 233, 248, 239, 233, 231, 231, 231, 231, 254, 233, 233, 235, 254, 255, 231, 254, 237, 236, 254, 239, 235, 235, 233, 233, 232, 232, 233, 232, 0, 0],
  [0, 0, 0, 232, 233, 246, 255, 255, 236, 236, 236, 236, 236, 255, 231, 231, 231, 231, 231, 231, 252, 234, 248, 231, 231, 231, 231, 248, 232, 232, 232, 0, 0, 0],
  [0, 0, 0, 0, 235, 237, 7, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 255, 238, 235, 7, 231, 231, 231, 246, 232, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 235, 103, 188, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 252, 232, 238, 231, 231, 255, 244, 232, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 235, 236, 103, 146, 253, 255, 231, 231, 231, 231, 231, 253, 251, 250, 250, 250, 246, 232, 235, 152, 255, 146, 66, 233, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 233, 103, 146, 146, 146, 146, 254, 231, 231, 231, 109, 103, 146, 255, 188, 239, 240, 103, 255, 253, 103, 238, 234, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 232, 235, 109, 146, 146, 146, 146, 146, 252, 152, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 103, 235, 233, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 235, 235, 103, 146, 146, 146, 146, 146, 146, 188, 188, 188, 188, 188, 188, 152, 146, 146, 146, 66, 235, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 233, 235, 66, 146, 146, 146, 146, 152, 255, 146, 240, 239, 241, 109, 146, 146, 146, 103, 233, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 234, 237, 109, 146, 146, 146, 146, 146, 254, 231, 231, 188, 146, 146, 146, 103, 233, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 237, 60, 103, 146, 146, 146, 146, 146, 103, 66, 60, 235, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 233, 233, 236, 235, 237, 235, 237, 237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
 
function visnup (args, cb) {
  handsomeFace.forEach(function (line) {
    output(line.map(function (ch) {
      return '\u001b[' + (ch ? '48;5;' + ch : ch) + 'm'
    }).join(' '))
  })
 
  var c = args.shift()
  if (c) npm.commands[c](args, cb)
  else cb()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/whoami.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/whoami.js

Statements: 16.13% (5 / 31)      Branches: 0% (0 / 18)      Functions: 0% (0 / 2)      Lines: 18.52% (5 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 491 1   1   1   1                                                                                  
var npm = require('./npm.js')
var output = require('./utils/output.js')
 
module.exports = whoami
 
whoami.usage = 'npm whoami [--registry <registry>]\n(just prints username according to given registry)'
 
function whoami (args, silent, cb) {
  // FIXME: need tighter checking on this, but is a breaking change
  if (typeof cb !== 'function') {
    cb = silent
    silent = false
  }
 
  var registry = npm.config.get('registry')
  if (!registry) return cb(new Error('no default registry set'))
 
  var auth = npm.config.getCredentialsByURI(registry)
  if (auth) {
    if (auth.username) {
      if (!silent) output(auth.username)
      return process.nextTick(cb.bind(this, null, auth.username))
    } else if (auth.token) {
      return npm.registry.whoami(registry, { auth: auth }, function (er, username) {
        if (er) return cb(er)
        if (!username) {
          var needNewSession = new Error(
            'Your auth token is no longer valid. Please log in again.'
          )
          needNewSession.code = 'ENEEDAUTH'
          return cb(needNewSession)
        }
 
        if (!silent) output(username)
        cb(null, username)
      })
    }
  }
 
  // At this point, if they have a credentials object, it doesn't have a token
  // or auth in it.  Probably just the default registry.
  var needAuth = new Error(
    'this command requires you to be logged in.'
  )
  needAuth.code = 'ENEEDAUTH'
  process.nextTick(cb.bind(this, needAuth))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/xmas.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/xmas.js

Statements: 10% (5 / 50)      Branches: 0% (0 / 8)      Functions: 0% (0 / 5)      Lines: 11.9% (5 / 42)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61  1   1                         1                                                                         1 1            
// happy xmas
var log = require('npmlog')
 
module.exports = function (args, cb) {
  var s = process.platform === 'win32' ? ' *' : ' \u2605'
  var f = '\uFF0F'
  var b = '\uFF3C'
  var x = process.platform === 'win32' ? ' ' : ''
  var o = [
    '\u0069', '\u0020', '\u0020', '\u0020', '\u0020', '\u0020',
    '\u0020', '\u0020', '\u0020', '\u0020', '\u0020', '\u0020',
    '\u0020', '\u2E1B', '\u2042', '\u2E2E', '&', '@', '\uFF61'
  ]
  var oc = [21, 33, 34, 35, 36, 37]
  var l = '\u005e'
 
  function w (s) { process.stderr.write(s) }
 
  w('\n')
  ;(function T (H) {
    for (var i = 0; i < H; i++) w(' ')
    w(x + '\u001b[33m' + s + '\n')
    var M = H * 2 - 1
    for (var L = 1; L <= H; L++) {
      var O = L * 2 - 2
      var S = (M - O) / 2
      for (i = 0; i < S; i++) w(' ')
      w(x + '\u001b[32m' + f)
      for (i = 0; i < O; i++) {
        w(
          '\u001b[' + oc[Math.floor(Math.random() * oc.length)] + 'm' +
          o[Math.floor(Math.random() * o.length)]
        )
      }
      w(x + '\u001b[32m' + b + '\n')
    }
    w(' ')
    for (i = 1; i < H; i++) w('\u001b[32m' + l)
    w('| ' + x + ' |')
    for (i = 1; i < H; i++) w('\u001b[32m' + l)
    if (H > 10) {
      w('\n ')
      for (i = 1; i < H; i++) w(' ')
      w('| ' + x + ' |')
      for (i = 1; i < H; i++) w(' ')
    }
  })(20)
  w('\n\n')
  log.heading = ''
  log.addLevel('npm', 100000, log.headingStyle)
  log.npm('loves you', 'Happy Xmas, Noders!')
  cb()
}
var dg = false
Object.defineProperty(module.exports, 'usage', {get: function () {
  if (dg) module.exports([], function () {})
  dg = true
  return ' '
}})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/

Statements: 20.34% (178 / 875)      Branches: 0% (0 / 455)      Functions: 0% (0 / 132)      Lines: 22.19% (178 / 802)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/cache/
File Statements Branches Functions Lines
add-local-tarball.js 23.68% (27 / 114) 0% (0 / 57) 0% (0 / 18) 25.96% (27 / 104)
add-local.js 27.17% (25 / 92) 0% (0 / 60) 0% (0 / 11) 29.41% (25 / 85)
add-named.js 17.71% (34 / 192) 0% (0 / 123) 0% (0 / 23) 19.77% (34 / 172)
add-remote-git.js 14.34% (39 / 272) 0% (0 / 116) 0% (0 / 47) 15.85% (39 / 246)
add-remote-tarball.js 28% (21 / 75) 0% (0 / 30) 0% (0 / 15) 29.58% (21 / 71)
cached-package-root.js 55.56% (5 / 9) 100% (0 / 0) 0% (0 / 1) 55.56% (5 / 9)
caching-client.js 20.51% (24 / 117) 0% (0 / 69) 0% (0 / 16) 21.62% (24 / 111)
get-stat.js 75% (3 / 4) 100% (0 / 0) 0% (0 / 1) 75% (3 / 4)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-local-tarball.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-local-tarball.js

Statements: 23.68% (27 / 114)      Branches: 0% (0 / 57)      Functions: 0% (0 / 18)      Lines: 25.96% (27 / 104)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 1771 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1   1                                                               1                   1                                           1                                                                                                               1                               1                       1            
var mkdir = require('mkdirp')
var assert = require('assert')
var fs = require('graceful-fs')
var writeFileAtomic = require('write-file-atomic')
var path = require('path')
var sha = require('sha')
var npm = require('../npm.js')
var log = require('npmlog')
var tar = require('../utils/tar.js')
var pathIsInside = require('path-is-inside')
var getCacheStat = require('./get-stat.js')
var cachedPackageRoot = require('./cached-package-root.js')
var chownr = require('chownr')
var inflight = require('inflight')
var once = require('once')
var writeStreamAtomic = require('fs-write-stream-atomic')
var tempFilename = require('../utils/temp-filename.js')
var rimraf = require('rimraf')
var packageId = require('../utils/package-id.js')
 
module.exports = addLocalTarball
 
function addLocalTarball (p, pkgData, shasum, cb) {
  assert(typeof p === 'string', 'must have path')
  assert(typeof cb === 'function', 'must have callback')
 
  if (!pkgData) pkgData = {}
 
  // If we don't have a shasum yet, compute it.
  if (!shasum) {
    return sha.get(p, function (er, shasum) {
      if (er) return cb(er)
      log.silly('addLocalTarball', 'shasum (computed)', shasum)
      addLocalTarball(p, pkgData, shasum, cb)
    })
  }
 
  if (pathIsInside(p, npm.cache)) {
    if (path.basename(p) !== 'package.tgz') {
      return cb(new Error('Not a valid cache tarball name: ' + p))
    }
    log.verbose('addLocalTarball', 'adding from inside cache', p)
    return addPlacedTarball(p, pkgData, shasum, cb)
  }
 
  addTmpTarball(p, pkgData, shasum, function (er, data) {
    if (data) {
      data._resolved = p
      data._shasum = data._shasum || shasum
    }
    return cb(er, data)
  })
}
 
function addPlacedTarball (p, pkgData, shasum, cb) {
  assert(pkgData, 'should have package data by now')
  assert(typeof cb === 'function', 'cb function required')
 
  getCacheStat(function (er, cs) {
    if (er) return cb(er)
    return addPlacedTarball_(p, pkgData, cs.uid, cs.gid, shasum, cb)
  })
}
 
function addPlacedTarball_ (p, pkgData, uid, gid, resolvedSum, cb) {
  var folder = path.join(cachedPackageRoot(pkgData), 'package')
 
  // First, make sure we have the shasum, if we don't already.
  if (!resolvedSum) {
    sha.get(p, function (er, shasum) {
      if (er) return cb(er)
      addPlacedTarball_(p, pkgData, uid, gid, shasum, cb)
    })
    return
  }
 
  mkdir(folder, function (er) {
    if (er) return cb(er)
    var pj = path.join(folder, 'package.json')
    var json = JSON.stringify(pkgData, null, 2)
    writeFileAtomic(pj, json, function (er) {
      cb(er, pkgData)
    })
  })
}
 
function addTmpTarball (tgz, pkgData, shasum, cb) {
  assert(typeof cb === 'function', 'must have callback function')
  assert(shasum, 'must have shasum by now')
 
  cb = inflight('addTmpTarball:' + tgz, cb)
  if (!cb) return log.verbose('addTmpTarball', tgz, 'already in flight; not adding')
  log.verbose('addTmpTarball', tgz, 'not in flight; adding')
 
  // we already have the package info, so just move into place
  if (pkgData && pkgData.name && pkgData.version) {
    log.verbose(
      'addTmpTarball',
      'already have metadata; skipping unpack for',
      packageId(pkgData)
    )
    return addTmpTarball_(tgz, pkgData, shasum, cb)
  }
 
  // This is a tarball we probably downloaded from the internet.  The shasum's
  // already been checked, but we haven't ever had a peek inside, so we unpack
  // it here just to make sure it is what it says it is.
  //
  // NOTE: we might not have any clue what we think it is, for example if the
  // user just did `npm install ./foo.tgz`
 
  var target = tempFilename('unpack')
  getCacheStat(function (er, cs) {
    if (er) return cb(er)
 
    log.verbose('addTmpTarball', 'validating metadata from', tgz)
    tar.unpack(tgz, target, null, null, cs.uid, cs.gid, function (unpackEr, data) {
      // cleanup the extracted package and move on with the metadata
      rimraf(target, function () {
        if (unpackEr) return cb(unpackEr)
        // check that this is what we expected.
        if (!data.name) {
          return cb(new Error('No name provided'))
        } else if (pkgData.name && data.name !== pkgData.name) {
          return cb(new Error('Invalid Package: expected ' + pkgData.name +
                              ' but found ' + data.name))
        }
 
        if (!data.version) {
          return cb(new Error('No version provided'))
        } else if (pkgData.version && data.version !== pkgData.version) {
          return cb(new Error('Invalid Package: expected ' +
                              packageId(pkgData) +
                              ' but found ' + packageId(data)))
        }
 
        addTmpTarball_(tgz, data, shasum, cb)
      })
    })
  })
}
 
function addTmpTarball_ (tgz, data, shasum, cb) {
  assert(typeof cb === 'function', 'must have callback function')
  cb = once(cb)
 
  assert(data.name, 'should have package name by now')
  assert(data.version, 'should have package version by now')
 
  var root = cachedPackageRoot(data)
  var pkg = path.resolve(root, 'package')
  var target = path.resolve(root, 'package.tgz')
  getCacheStat(function (er, cs) {
    if (er) return cb(er)
    mkdir(pkg, function (er, created) {
      // chown starting from the first dir created by mkdirp,
      // or the root dir, if none had to be created, so that
      // we know that we get all the children.
      function chown () {
        chownr(created || root, cs.uid, cs.gid, done)
      }
 
      if (er) return cb(er)
      var read = fs.createReadStream(tgz)
      var write = writeStreamAtomic(target, { mode: npm.modes.file })
      var fin = cs.uid && cs.gid ? chown : done
      read.on('error', cb).pipe(write).on('error', cb).on('close', fin)
    })
  })
 
  function done () {
    data._shasum = data._shasum || shasum
    cb(null, data)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-local.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-local.js

Statements: 27.17% (25 / 92)      Branches: 0% (0 / 60)      Functions: 0% (0 / 11)      Lines: 29.41% (25 / 85)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 1551 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1   1           1                                           1                                                                                                                                       1                                   1                                    
var assert = require('assert')
var path = require('path')
var mkdir = require('mkdirp')
var chownr = require('chownr')
var pathIsInside = require('path-is-inside')
var readJson = require('read-package-json')
var log = require('npmlog')
var npm = require('../npm.js')
var tar = require('../utils/tar.js')
var deprCheck = require('../utils/depr-check.js')
var prepublishWarning = require('../utils/warn-deprecated.js')('prepublish-on-install')
var getCacheStat = require('./get-stat.js')
var cachedPackageRoot = require('./cached-package-root.js')
var addLocalTarball = require('./add-local-tarball.js')
var sha = require('sha')
var inflight = require('inflight')
var lifecycle = require('../utils/lifecycle.js')
var iferr = require('iferr')
var chain = require('slide').chain
 
module.exports = addLocal
 
function addLocal (p, pkgData, cb_) {
  assert(typeof p === 'object', 'must have spec info')
  assert(typeof cb_ === 'function', 'must have callback')
 
  pkgData = pkgData || {}
 
  function cb (er, data) {
    if (er) {
      log.error('addLocal', 'Could not install %s', p.spec)
      return cb_(er)
    }
    if (data && !data._fromHosted) {
      data._from = path.relative(npm.prefix, p.spec) || '.'
      var resolved = path.relative(npm.prefix, p.spec)
      if (resolved) data._resolved = 'file:' + resolved
    }
    return cb_(er, data)
  }
 
  if (p.type === 'directory') {
    addLocalDirectory(p.spec, pkgData, null, cb)
  } else {
    addLocalTarball(p.spec, pkgData, null, cb)
  }
}
 
// At this point, if shasum is set, it's something that we've already
// read and checked.  Just stashing it in the data at this point.
function addLocalDirectory (p, pkgData, shasum, cb) {
  assert(pkgData, 'must pass package data')
  assert(typeof cb === 'function', 'must have callback')
 
  // if it's a folder, then read the package.json,
  // tar it to the proper place, and add the cache tar
  if (pathIsInside(p, npm.cache)) {
    return cb(new Error(
    'Adding a cache directory to the cache will make the world implode.'
    ))
  }
 
  readJson(path.join(p, 'package.json'), false, function (er, data) {
    if (er) return cb(er)
 
    if (!data.name) {
      return cb(new Error('No name provided in package.json'))
    } else if (pkgData.name && pkgData.name !== data.name) {
      return cb(new Error(
        'Invalid package: expected ' + pkgData.name + ' but found ' + data.name
      ))
    }
 
    if (!data.version) {
      return cb(new Error('No version provided in package.json'))
    } else if (pkgData.version && pkgData.version !== data.version) {
      return cb(new Error(
        'Invalid package: expected ' + pkgData.name + '@' + pkgData.version +
          ' but found ' + data.name + '@' + data.version
      ))
    }
 
    deprCheck(data)
 
    // pack to {cache}/name/ver/package.tgz
    var root = cachedPackageRoot(data)
    var tgz = path.resolve(root, 'package.tgz')
    var pj = path.resolve(root, 'package/package.json')
 
    var wrapped = inflight(tgz, next)
    if (!wrapped) return log.verbose('addLocalDirectory', tgz, 'already in flight; waiting')
    log.verbose('addLocalDirectory', tgz, 'not in flight; packing')
 
    getCacheStat(function (er, cs) {
      mkdir(path.dirname(pj), function (er, made) {
        if (er) return wrapped(er)
        var doPrePublish = !pathIsInside(p, npm.tmp)
        if (doPrePublish) {
          // TODO: for `npm@5`, change the behavior and remove this warning.
          // see https://github.com/npm/npm/issues/10074 for details
          if (data && data.scripts && data.scripts.prepublish) {
            prepublishWarning([
              'As of npm@5, `prepublish` scripts will run only for `npm publish`.',
              '(In npm@4 and previous versions, it also runs for `npm install`.)',
              'See the deprecation note in `npm help scripts` for more information.'
            ])
          }
 
          chain(
            [
              [lifecycle, data, 'prepublish', p],
              [lifecycle, data, 'prepare', p]
            ],
            iferr(wrapped, thenPack)
          )
        } else {
          thenPack()
        }
        function thenPack () {
          tar.pack(tgz, p, data, function (er) {
            if (er) {
              log.error('addLocalDirectory', 'Could not pack', p, 'to', tgz)
              return wrapped(er)
            }
 
            if (!cs || isNaN(cs.uid) || isNaN(cs.gid)) return wrapped()
 
            chownr(made || tgz, cs.uid, cs.gid, function (er) {
              if (er && er.code === 'ENOENT') return wrapped()
              wrapped(er)
            })
          })
        }
      })
    })
 
    function next (er) {
      if (er) return cb(er)
      // if we have the shasum already, just add it
      if (shasum) {
        return addLocalTarball(tgz, data, shasum, cb)
      } else {
        sha.get(tgz, function (er, shasum) {
          if (er) {
            return cb(er)
          }
          data._shasum = shasum
          return addLocalTarball(tgz, data, shasum, cb)
        })
      }
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-named.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-named.js

Statements: 17.71% (34 / 192)      Branches: 0% (0 / 123)      Functions: 0% (0 / 23)      Lines: 19.77% (34 / 172)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 2911 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1   1 1                                               1             1                                 1                   1                                         1                                   1                         1                               1                                                                                   1                                                                 1                           1                 1                                 1                                 1                      
var path = require('path')
var assert = require('assert')
var fs = require('graceful-fs')
var http = require('http')
var log = require('npmlog')
var semver = require('semver')
var readJson = require('read-package-json')
var url = require('url')
var npm = require('../npm.js')
var deprCheck = require('../utils/depr-check.js')
var inflight = require('inflight')
var addRemoteTarball = require('./add-remote-tarball.js')
var cachedPackageRoot = require('./cached-package-root.js')
var mapToRegistry = require('../utils/map-to-registry.js')
var pulseTillDone = require('../utils/pulse-till-done.js')
var packageId = require('../utils/package-id.js')
var pickManifestFromRegistryMetadata = require('../utils/pick-manifest-from-registry-metadata.js')
 
module.exports = addNamed
 
function getOnceFromRegistry (name, from, next, done) {
  function fixName (err, data, json, resp) {
    // this is only necessary until npm/npm-registry-client#80 is fixed
    if (err && err.pkgid && err.pkgid !== name) {
      err.message = err.message.replace(
        new RegExp(': ' + err.pkgid.replace(/(\W)/g, '\\$1') + '$'),
        ': ' + name
      )
      err.pkgid = name
    }
    next(err, data, json, resp)
  }
 
  mapToRegistry(name, npm.config, function (er, uri, auth) {
    if (er) return done(er)
 
    var key = 'registry:' + uri
    next = inflight(key, next)
    if (!next) return log.verbose(from, key, 'already in flight; waiting')
    else log.verbose(from, key, 'not in flight; fetching')
 
    npm.registry.get(uri, { auth: auth }, pulseTillDone('fetchRegistry', fixName))
  })
}
 
function addNamed (name, version, data, cb_) {
  assert(typeof name === 'string', 'must have module name')
  assert(typeof cb_ === 'function', 'must have callback')
 
  var key = name + '@' + version
  log.silly('addNamed', key)
 
  function cb (er, data) {
    if (data && !data._fromHosted) data._from = key
    cb_(er, data)
  }
 
  if (semver.valid(version, true)) {
    log.verbose('addNamed', JSON.stringify(version), 'is a plain semver version for', name)
    addNameVersion(name, version, data, cb)
  } else if (semver.validRange(version, true)) {
    log.verbose('addNamed', JSON.stringify(version), 'is a valid semver range for', name)
    addNameRange(name, version, data, cb)
  } else {
    log.verbose('addNamed', JSON.stringify(version), 'is being treated as a dist-tag for', name)
    addNameTag(name, version, data, cb)
  }
}
 
function addNameTag (name, tag, data, cb) {
  log.info('addNameTag', [name, tag])
  var explicit = true
  if (!tag) {
    explicit = false
    tag = npm.config.get('tag')
  }
 
  getOnceFromRegistry(name, 'addNameTag', next, cb)
 
  function next (er, data, json, resp) {
    if (!er) er = errorResponse(name, resp)
    if (er) return cb(er)
 
    log.silly('addNameTag', 'next cb for', name, 'with tag', tag)
 
    engineFilter(data)
    if (data['dist-tags'] && data['dist-tags'][tag] &&
        data.versions[data['dist-tags'][tag]]) {
      var ver = data['dist-tags'][tag]
      return addNamed(name, ver, data.versions[ver], cb)
    }
    if (!explicit && Object.keys(data.versions).length) {
      return addNamed(name, '*', data, cb)
    }
 
    er = installTargetsError(tag, data)
    return cb(er)
  }
}
 
function engineFilter (data) {
  var npmv = npm.version
  var nodev = npm.config.get('node-version')
  var strict = npm.config.get('engine-strict')
 
  if (!nodev || npm.config.get('force')) return data
 
  Object.keys(data.versions || {}).forEach(function (v) {
    var eng = data.versions[v].engines
    if (!eng) return
    if (!strict) return
    if (eng.node && !semver.satisfies(nodev, eng.node, true) ||
        eng.npm && !semver.satisfies(npmv, eng.npm, true)) {
      delete data.versions[v]
    }
  })
}
 
function addNameVersion (name, v, data, cb) {
  var ver = semver.valid(v, true)
  if (!ver) return cb(new Error('Invalid version: ' + v))
 
  var response
 
  if (data) {
    response = null
    return next()
  }
 
  getOnceFromRegistry(name, 'addNameVersion', setData, cb)
 
  function setData (er, d, json, resp) {
    if (!er) {
      er = errorResponse(name, resp)
    }
    if (er) return cb(er)
    data = d && d.versions[ver]
    if (!data) {
      er = new Error('version not found: ' + name + '@' + ver)
      er.package = name
      er.statusCode = 404
      return cb(er)
    }
    response = resp
    next()
  }
 
  function next () {
    deprCheck(data)
    var dist = data.dist
 
    if (!dist) return cb(new Error('No dist in ' + packageId(data) + ' package'))
 
    if (!dist.tarball) {
      return cb(new Error(
      'No dist.tarball in ' + packageId(data) + ' package'
      ))
    }
 
    if ((response && response.statusCode !== 304) || npm.config.get('force')) {
      return fetchit()
    }
 
    // we got cached data, so let's see if we have a tarball.
    var pkgroot = cachedPackageRoot({ name: name, version: ver })
    var pkgtgz = path.join(pkgroot, 'package.tgz')
    var pkgjson = path.join(pkgroot, 'package', 'package.json')
    fs.stat(pkgtgz, function (er) {
      if (!er) {
        readJson(pkgjson, function (er, data) {
          if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
 
          if (data) {
            if (!data.name) return cb(new Error('No name provided'))
            if (!data.version) return cb(new Error('No version provided'))
 
            // check the SHA of the package we have, to ensure it wasn't installed
            // from somewhere other than the registry (eg, a fork)
            if (data._shasum && dist.shasum && data._shasum !== dist.shasum) {
              return fetchit()
            }
          }
 
          if (er) return fetchit()
            else return cb(null, data)
        })
      } else return fetchit()
    })
 
    function fetchit () {
      mapToRegistry(name, npm.config, function (er, _, auth, ruri) {
        if (er) return cb(er)
 
        // Use the same protocol as the registry.  https registry --> https
        // tarballs, but only if they're the same hostname, or else detached
        // tarballs may not work.
        var tb = url.parse(dist.tarball)
        var rp = url.parse(ruri)
        if (tb.hostname === rp.hostname && tb.protocol !== rp.protocol) {
          tb.protocol = rp.protocol
          // If a different port is associated with the other protocol
          // we need to update that as well
          if (rp.port !== tb.port) {
            tb.port = rp.port
            delete tb.host
          }
          delete tb.href
        }
        tb = url.format(tb)
 
        // Only add non-shasum'ed packages if --forced. Only ancient things
        // would lack this for good reasons nowadays.
        if (!dist.shasum && !npm.config.get('force')) {
          return cb(new Error('package lacks shasum: ' + packageId(data)))
        }
 
        addRemoteTarball(tb, data, dist.shasum, auth, cb)
      })
    }
  }
}
 
function addNameRange (name, range, data, cb) {
  range = semver.validRange(range, true)
  if (range === null) {
    return cb(new Error(
      'Invalid version range: ' + range
    ))
  }
 
  log.silly('addNameRange', { name: name, range: range, hasData: !!data })
 
  if (data) return next()
 
  getOnceFromRegistry(name, 'addNameRange', setData, cb)
 
  function setData (er, d, json, resp) {
    if (!er) {
      er = errorResponse(name, resp)
    }
    if (er) return cb(er)
    data = d
    next()
  }
 
  function next () {
    log.silly(
      'addNameRange',
      'number 2', { name: name, range: range, hasData: !!data }
    )
    engineFilter(data)
 
    log.silly('addNameRange', 'versions'
             , [data.name, Object.keys(data.versions || {})])
 
    var versions = Object.keys(data.versions).filter(function (v) { return semver.valid(v) })
    var picked = pickManifestFromRegistryMetadata(range, npm.config.get('tag'), versions, data)
    if (picked) return addNamed(name, picked.resolvedTo, picked.manifest, cb)
    return cb(installTargetsError(range, data))
  }
}
 
function installTargetsError (requested, data) {
  var targets = Object.keys(data['dist-tags']).filter(function (f) {
    return (data.versions || {}).hasOwnProperty(f)
  }).concat(Object.keys(data.versions || {}))
 
  requested = data.name + (requested ? "@'" + requested + "'" : '')
 
  targets = targets.length
          ? 'Valid install targets:\n' + targets.join(', ') + '\n'
          : 'No valid targets found.\n' +
            'Perhaps not compatible with your version of node?'
 
  var er = new Error('No compatible version found: ' + requested + '\n' + targets)
  er.code = 'ETARGET'
  return er
}
 
function errorResponse (name, response) {
  var er
  if (response.statusCode >= 400) {
    er = new Error(http.STATUS_CODES[response.statusCode])
    er.statusCode = response.statusCode
    er.code = 'E' + er.statusCode
    er.pkgid = name
  }
  return er
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-remote-git.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-remote-git.js

Statements: 14.34% (39 / 272)      Branches: 0% (0 / 116)      Functions: 0% (0 / 47)      Lines: 15.85% (39 / 246)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 49828 28 28 28   28 28 28 28 28 28 28 28 28 28   28 28 28                                     1                                                                               1                       1                           1               1                                                         1                   1                   1                                                                 1                                                             1                                                           1                                           1                                                                             1                                         1                                   1                                                                                     1                                     1                                   1                                                   1                         1               1                 1              
var assert = require('assert')
var fs = require('graceful-fs')
var path = require('path')
var url = require('url')
 
var chownr = require('chownr')
var dezalgo = require('dezalgo')
var hostedFromURL = require('hosted-git-info').fromUrl
var inflight = require('inflight')
var log = require('npmlog')
var mkdir = require('mkdirp')
var normalizeGitUrl = require('normalize-git-url')
var npa = require('npm-package-arg')
var realizePackageSpecifier = require('realize-package-specifier')
var uniqueFilename = require('unique-filename')
 
var addLocal = require('./add-local.js')
var correctMkdir = require('../utils/correct-mkdir.js')
var git = require('../utils/git.js')
var npm = require('../npm.js')
var rm = require('../utils/gently-rm.js')
var tempFilename = require('../utils/temp-filename.js')
 
var remotes = path.resolve(npm.config.get('cache'), '_git-remotes')
var templates = path.join(remotes, '_templates')
 
var VALID_VARIABLES = [
  'GIT_ASKPASS',
  'GIT_EXEC_PATH',
  'GIT_PROXY_COMMAND',
  'GIT_SSH',
  'GIT_SSH_COMMAND',
  'GIT_SSL_CAINFO',
  'GIT_SSL_NO_VERIFY'
]
 
module.exports = addRemoteGit
function addRemoteGit (uri, _cb) {
  assert(typeof uri === 'string', 'must have git URL')
  assert(typeof _cb === 'function', 'must have callback')
  var cb = dezalgo(_cb)
 
  log.verbose('addRemoteGit', 'caching', uri)
 
  // the URL comes in exactly as it was passed on the command line, or as
  // normalized by normalize-package-data / read-package-json / read-installed,
  // so figure out what to do with it using hosted-git-info
  var parsed = hostedFromURL(uri)
  if (parsed) {
    // normalize GitHub syntax to org/repo (for now)
    var from
    if (parsed.type === 'github' && parsed.getDefaultRepresentation() === 'shortcut') {
      from = parsed.path()
    } else {
      from = parsed.toString()
    }
 
    log.verbose('addRemoteGit', from, 'is a repository hosted by', parsed.type)
 
    // prefer explicit URLs to pushing everything through shortcuts
    if (parsed.getDefaultRepresentation() !== 'shortcut') {
      return tryClone(from, parsed.toString(), false, cb)
    }
 
    // try git:, then git+ssh:, then git+https: before failing
    tryGitProto(from, parsed, cb)
  } else {
    // verify that this is a Git URL before continuing
    parsed = npa(uri)
    if (parsed.type !== 'git') {
      return cb(new Error(uri + 'is not a Git or GitHub URL'))
    }
 
    tryClone(parsed.rawSpec, uri, false, cb)
  }
}
 
function tryGitProto (from, hostedInfo, cb) {
  var gitURL = hostedInfo.git()
  if (!gitURL) return tryHTTPS(from, hostedInfo, cb)
 
  log.silly('tryGitProto', 'attempting to clone', gitURL)
  tryClone(from, gitURL, true, function (er) {
    if (er) return tryHTTPS(from, hostedInfo, cb)
 
    cb.apply(this, arguments)
  })
}
 
function tryHTTPS (from, hostedInfo, cb) {
  var httpsURL = hostedInfo.https()
  if (!httpsURL) {
    return cb(new Error(from + ' can not be cloned via Git, SSH, or HTTPS'))
  }
 
  log.silly('tryHTTPS', 'attempting to clone', httpsURL)
  tryClone(from, httpsURL, true, function (er) {
    if (er) return trySSH(from, hostedInfo, cb)
 
    cb.apply(this, arguments)
  })
}
 
function trySSH (from, hostedInfo, cb) {
  var sshURL = hostedInfo.ssh()
  if (!sshURL) return tryHTTPS(from, hostedInfo, cb)
 
  log.silly('trySSH', 'attempting to clone', sshURL)
  tryClone(from, sshURL, false, cb)
}
 
function tryClone (from, combinedURL, silent, cb) {
  log.silly('tryClone', 'cloning', from, 'via', combinedURL)
 
  var normalized = normalizeGitUrl(combinedURL)
  var cloneURL = normalized.url
  var treeish = normalized.branch
 
  // ensure that similarly-named remotes don't collide
  var cachedRemote = uniqueFilename(remotes, combinedURL.replace(/[^a-zA-Z0-9]+/g, '-'), cloneURL)
  var repoID = path.relative(remotes, cachedRemote)
  cachedRemote = path.join(remotes, repoID)
 
  cb = inflight(repoID, cb)
  if (!cb) {
    return log.verbose('tryClone', repoID, 'already in flight; waiting')
  }
  log.verbose('tryClone', repoID, 'not in flight; caching')
 
  // initialize the remotes cache with the correct perms
  getGitDir(function (er) {
    if (er) return cb(er)
    fs.stat(cachedRemote, function (er, s) {
      if (er) return mirrorRemote(from, cloneURL, treeish, cachedRemote, silent, finish)
      if (!s.isDirectory()) return resetRemote(from, cloneURL, treeish, cachedRemote, finish)
 
      validateExistingRemote(from, cloneURL, treeish, cachedRemote, finish)
    })
 
    // always set permissions on the cached remote
    function finish (er, data) {
      if (er) return cb(er, data)
      addModeRecursive(cachedRemote, npm.modes.file, function (er) {
        return cb(er, data)
      })
    }
  })
}
 
// don't try too hard to hold on to a remote
function resetRemote (from, cloneURL, treeish, cachedRemote, cb) {
  log.info('resetRemote', 'resetting', cachedRemote, 'for', from)
  rm(cachedRemote, function (er) {
    if (er) return cb(er)
    mirrorRemote(from, cloneURL, treeish, cachedRemote, false, cb)
  })
}
 
// reuse a cached remote when possible, but nuke it if it's in an
// inconsistent state
function validateExistingRemote (from, cloneURL, treeish, cachedRemote, cb) {
  git.whichAndExec(
    ['config', '--get', 'remote.origin.url'],
    { cwd: cachedRemote, env: gitEnv() },
    function (er, stdout, stderr) {
      var originURL
      if (stdout) {
        originURL = stdout.trim()
        log.silly('validateExistingRemote', from, 'remote.origin.url:', originURL)
      }
 
      if (stderr) stderr = stderr.trim()
      if (stderr || er) {
        log.warn('addRemoteGit', from, 'resetting remote', cachedRemote, 'because of error:', stderr || er)
        return resetRemote(from, cloneURL, treeish, cachedRemote, cb)
      } else if (cloneURL !== originURL) {
        log.warn(
          'addRemoteGit',
          from,
          'pre-existing cached repo', cachedRemote, 'points to', originURL, 'and not', cloneURL
        )
        return resetRemote(from, cloneURL, treeish, cachedRemote, cb)
      }
 
      log.verbose('validateExistingRemote', from, 'is updating existing cached remote', cachedRemote)
      updateRemote(from, cloneURL, treeish, cachedRemote, cb)
    }
  )
}
 
// make a complete bare mirror of the remote repo
// NOTE: npm uses a blank template directory to prevent weird inconsistencies
// https://github.com/npm/npm/issues/5867
function mirrorRemote (from, cloneURL, treeish, cachedRemote, silent, cb) {
  mkdir(cachedRemote, function (er) {
    if (er) return cb(er)
 
    var args = [
      'clone',
      '--template=' + templates,
      '--mirror',
      cloneURL, cachedRemote
    ]
    git.whichAndExec(
      ['clone', '--template=' + templates, '--mirror', cloneURL, cachedRemote],
      { cwd: cachedRemote, env: gitEnv() },
      function (er, stdout, stderr) {
        if (er) {
          var combined = (stdout + '\n' + stderr).trim()
          var command = 'git ' + args.join(' ') + ':'
          if (silent) {
            log.verbose(command, combined)
          } else {
            log.error(command, combined)
          }
          return cb(er)
        }
        log.verbose('mirrorRemote', from, 'git clone ' + cloneURL, stdout.trim())
        setPermissions(from, cloneURL, treeish, cachedRemote, cb)
      }
    )
  })
}
 
function setPermissions (from, cloneURL, treeish, cachedRemote, cb) {
  if (process.platform === 'win32') {
    log.verbose('setPermissions', from, 'skipping chownr on Windows')
    resolveHead(from, cloneURL, treeish, cachedRemote, cb)
  } else {
    getGitDir(function (er, cs) {
      if (er) {
        log.error('setPermissions', from, 'could not get cache stat')
        return cb(er)
      }
 
      chownr(cachedRemote, cs.uid, cs.gid, function (er) {
        if (er) {
          log.error(
            'setPermissions',
            'Failed to change git repository ownership under npm cache for',
            cachedRemote
          )
          return cb(er)
        }
 
        log.verbose('setPermissions', from, 'set permissions on', cachedRemote)
        resolveHead(from, cloneURL, treeish, cachedRemote, cb)
      })
    })
  }
}
 
// always fetch the origin, even right after mirroring, because this way
// permissions will get set correctly
function updateRemote (from, cloneURL, treeish, cachedRemote, cb) {
  git.whichAndExec(
    ['fetch', '-a', 'origin'],
    { cwd: cachedRemote, env: gitEnv() },
    function (er, stdout, stderr) {
      if (er) {
        var combined = (stdout + '\n' + stderr).trim()
        log.error('git fetch -a origin (' + cloneURL + ')', combined)
        return cb(er)
      }
      log.verbose('updateRemote', 'git fetch -a origin (' + cloneURL + ')', stdout.trim())
 
      setPermissions(from, cloneURL, treeish, cachedRemote, cb)
    }
  )
}
 
// branches and tags are both symbolic labels that can be attached to different
// commits, so resolve the commit-ish to the current actual treeish the label
// corresponds to
//
// important for shrinkwrap
function resolveHead (from, cloneURL, treeish, cachedRemote, cb) {
  log.verbose('resolveHead', from, 'original treeish:', treeish)
  var args = ['rev-list', '-n1', treeish]
  git.whichAndExec(
    args,
    { cwd: cachedRemote, env: gitEnv() },
    function (er, stdout, stderr) {
      if (er) {
        log.error('git ' + args.join(' ') + ':', stderr)
        return cb(er)
      }
 
      var resolvedTreeish = stdout.trim()
      log.silly('resolveHead', from, 'resolved treeish:', resolvedTreeish)
 
      var resolvedURL = getResolved(cloneURL, resolvedTreeish)
      if (!resolvedURL) {
        return cb(new Error(
          'unable to clone ' + from + ' because git clone string ' +
            cloneURL + ' is in a form npm can\'t handle'
        ))
      }
      log.verbose('resolveHead', from, 'resolved Git URL:', resolvedURL)
 
      // generate a unique filename
      var tmpdir = path.join(tempFilename('git-cache'), resolvedTreeish)
      log.silly('resolveHead', 'Git working directory:', tmpdir)
 
      mkdir(tmpdir, function (er) {
        if (er) return cb(er)
 
        cloneResolved(from, resolvedURL, resolvedTreeish, cachedRemote, tmpdir, cb)
      })
    }
  )
}
 
// make a clone from the mirrored cache so we have a temporary directory in
// which we can check out the resolved treeish
function cloneResolved (from, resolvedURL, resolvedTreeish, cachedRemote, tmpdir, cb) {
  var args = ['clone', cachedRemote, tmpdir]
  git.whichAndExec(
    args,
    { cwd: cachedRemote, env: gitEnv() },
    function (er, stdout, stderr) {
      stdout = (stdout + '\n' + stderr).trim()
      if (er) {
        log.error('git ' + args.join(' ') + ':', stderr)
        return cb(er)
      }
      log.verbose('cloneResolved', from, 'clone', stdout)
 
      checkoutTreeish(from, resolvedURL, resolvedTreeish, tmpdir, cb)
    }
  )
}
 
// there is no safe way to do a one-step clone to a treeish that isn't
// guaranteed to be a branch, so explicitly check out the treeish once it's
// cloned
function checkoutTreeish (from, resolvedURL, resolvedTreeish, tmpdir, cb) {
  var args = ['checkout', resolvedTreeish]
  git.whichAndExec(
    args,
    { cwd: tmpdir, env: gitEnv() },
    function (er, stdout, stderr) {
      stdout = (stdout + '\n' + stderr).trim()
      if (er) {
        log.error('git ' + args.join(' ') + ':', stderr)
        return cb(er)
      }
      log.verbose('checkoutTreeish', from, 'checkout', stdout)
 
      updateSubmodules(from, resolvedURL, tmpdir, cb)
    }
  )
}
 
function updateSubmodules (from, resolvedURL, tmpdir, cb) {
  var args = ['submodule', '-q', 'update', '--init', '--recursive']
  git.whichAndExec(
    args,
    { cwd: tmpdir, env: gitEnv() },
    function (er, stdout, stderr) {
      stdout = (stdout + '\n' + stderr).trim()
      if (er) {
        log.error('git ' + args.join(' ') + ':', stderr)
        return cb(er)
      }
      log.verbose('updateSubmodules', from, 'submodule update', stdout)
 
      // convince addLocal that the checkout is a local dependency
      realizePackageSpecifier(tmpdir, function (er, spec) {
        if (er) {
          log.error('addRemoteGit', 'Failed to map', tmpdir, 'to a package specifier')
          return cb(er)
        }
 
        // ensure pack logic is applied
        // https://github.com/npm/npm/issues/6400
        addLocal(spec, null, function (er, data) {
          if (data) {
            if (npm.config.get('save-exact')) {
              log.verbose('addRemoteGit', 'data._from:', resolvedURL, '(save-exact)')
              data._from = resolvedURL
            } else {
              log.verbose('addRemoteGit', 'data._from:', from)
              data._from = from
            }
 
            log.verbose('addRemoteGit', 'data._resolved:', resolvedURL)
            data._resolved = resolvedURL
          }
 
          cb(er, data)
        })
      })
    }
  )
}
 
function getGitDir (cb) {
  correctMkdir(remotes, function (er, stats) {
    if (er) return cb(er)
 
    // We don't need global templates when cloning. Use an empty directory for
    // the templates, creating it (and setting its permissions) if necessary.
    mkdir(templates, function (er) {
      if (er) return cb(er)
 
      // Ensure that both the template and remotes directories have the correct
      // permissions.
      fs.chown(templates, stats.uid, stats.gid, function (er) {
        cb(er, stats)
      })
    })
  })
}
 
var gitEnv_
function gitEnv () {
  // git responds to env vars in some weird ways in post-receive hooks
  // so don't carry those along.
  if (gitEnv_) return gitEnv_
 
  // allow users to override npm's insistence on not prompting for
  // passphrases, but default to just failing when credentials
  // aren't available
  gitEnv_ = { GIT_ASKPASS: 'echo' }
 
  for (var k in process.env) {
    if (!~VALID_VARIABLES.indexOf(k) && k.match(/^GIT/)) continue
    gitEnv_[k] = process.env[k]
  }
  return gitEnv_
}
 
addRemoteGit.getResolved = getResolved
function getResolved (uri, treeish) {
  // normalize hosted-git-info clone URLs back into regular URLs
  // this will only work on URLs that hosted-git-info recognizes
  // https://github.com/npm/npm/issues/7961
  var rehydrated = hostedFromURL(uri)
  if (rehydrated) uri = rehydrated.toString()
 
  var parsed = url.parse(uri)
 
  // Checks for known protocols:
  // http:, https:, ssh:, and git:, with optional git+ prefix.
  if (!parsed.protocol ||
      !parsed.protocol.match(/^(((git\+)?(https?|ssh|file))|git|file):$/)) {
    uri = 'git+ssh://' + uri
  }
 
  if (!/^git[+:]/.test(uri)) {
    uri = 'git+' + uri
  }
 
  // Not all URIs are actually URIs, so use regex for the treeish.
  return uri.replace(/(?:#.*)?$/, '#' + treeish)
}
 
// similar to chmodr except it add permissions rather than overwriting them
// adapted from https://github.com/isaacs/chmodr/blob/master/chmodr.js
function addModeRecursive (cachedRemote, mode, cb) {
  fs.readdir(cachedRemote, function (er, children) {
    // Any error other than ENOTDIR means it's not readable, or doesn't exist.
    // Give up.
    if (er && er.code !== 'ENOTDIR') return cb(er)
    if (er || !children.length) return addMode(cachedRemote, mode, cb)
 
    var len = children.length
    var errState = null
    children.forEach(function (child) {
      addModeRecursive(path.resolve(cachedRemote, child), mode, then)
    })
 
    function then (er) {
      if (errState) return undefined
      if (er) return cb(errState = er)
      if (--len === 0) return addMode(cachedRemote, dirMode(mode), cb)
    }
  })
}
 
function addMode (cachedRemote, mode, cb) {
  fs.stat(cachedRemote, function (er, stats) {
    if (er) return cb(er)
    mode = stats.mode | mode
    fs.chmod(cachedRemote, mode, cb)
  })
}
 
// taken from https://github.com/isaacs/chmodr/blob/master/chmodr.js
function dirMode (mode) {
  if (mode & parseInt('0400', 8)) mode |= parseInt('0100', 8)
  if (mode & parseInt('040', 8)) mode |= parseInt('010', 8)
  if (mode & parseInt('04', 8)) mode |= parseInt('01', 8)
  return mode
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-remote-tarball.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/add-remote-tarball.js

Statements: 28% (21 / 75)      Branches: 0% (0 / 30)      Functions: 0% (0 / 15)      Lines: 29.58% (21 / 71)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 1341 1 1 1 1 1 1 1 1 1 1 1 1 1   1   1       1                                 1       1                           1                                                         1                                                                                                
var mkdir = require('mkdirp')
var assert = require('assert')
var log = require('npmlog')
var path = require('path')
var sha = require('sha')
var retry = require('retry')
var writeStreamAtomic = require('fs-write-stream-atomic')
var PassThrough = require('readable-stream').PassThrough
var npm = require('../npm.js')
var inflight = require('inflight')
var addLocalTarball = require('./add-local-tarball.js')
var cacheFile = require('npm-cache-filename')
var rimraf = require('rimraf')
var pulseTillDone = require('../utils/pulse-till-done.js')
 
module.exports = addRemoteTarball
 
function addRemoteTarball (u, pkgData, shasum, auth, cb_) {
  assert(typeof u === 'string', 'must have module URL')
  assert(typeof cb_ === 'function', 'must have callback')
 
  function cb (er, data) {
    if (data) {
      data._from = u
      data._resolved = u
      data._shasum = data._shasum || shasum
    }
    cb_(er, data)
  }
 
  cb_ = inflight(u, cb_)
  if (!cb_) return log.verbose('addRemoteTarball', u, 'already in flight; waiting')
  log.verbose('addRemoteTarball', u, 'not in flight; adding')
 
  // XXX Fetch direct to cache location, store tarballs under
  // ${cache}/registry.npmjs.org/pkg/-/pkg-1.2.3.tgz
  var tmp = cacheFile(npm.tmp, u)
 
  function next (er, resp, shasum) {
    if (er) return cb(er)
    addLocalTarball(tmp, pkgData, shasum, cleanup)
  }
  function cleanup (er, data) {
    if (er) return cb(er)
    rimraf(tmp, function () {
      cb(er, data)
    })
  }
 
  log.verbose('addRemoteTarball', [u, shasum])
  mkdir(path.dirname(tmp), function (er) {
    if (er) return cb(er)
    addRemoteTarball_(u, tmp, shasum, auth, next)
  })
}
 
function addRemoteTarball_ (u, tmp, shasum, auth, cb) {
  // Tuned to spread 3 attempts over about a minute.
  // See formula at <https://github.com/tim-kos/node-retry>.
  var operation = retry.operation({
    retries: npm.config.get('fetch-retries'),
    factor: npm.config.get('fetch-retry-factor'),
    minTimeout: npm.config.get('fetch-retry-mintimeout'),
    maxTimeout: npm.config.get('fetch-retry-maxtimeout')
  })
 
  operation.attempt(function (currentAttempt) {
    log.info(
      'retry',
      'fetch attempt', currentAttempt,
      'at', (new Date()).toLocaleTimeString()
    )
    fetchAndShaCheck(u, tmp, shasum, auth, function (er, response, shasum) {
      // Only retry on 408, 5xx or no `response`.
      var sc = response && response.statusCode
      var statusRetry = !sc || (sc === 408 || sc >= 500)
      if (er && statusRetry && operation.retry(er)) {
        log.warn('retry', 'will retry, error on last attempt: ' + er)
        return
      }
      cb(er, response, shasum)
    })
  })
}
 
function fetchAndShaCheck (u, tmp, shasum, auth, cb) {
  cb = pulseTillDone('fetchTarball', cb)
  npm.registry.fetch(u, { auth: auth }, function (er, response) {
    if (er) {
      log.error('fetch failed', u)
      return cb(er, response)
    }
 
    var tarball = writeStreamAtomic(tmp, { mode: npm.modes.file })
    tarball.on('error', function (er) {
      cb(er)
      tarball.destroy()
    })
 
    tarball.on('finish', function () {
      if (!shasum) {
        // Well, we weren't given a shasum, so at least sha what we have
        // in case we want to compare it to something else later
        return sha.get(tmp, function (er, shasum) {
          log.silly('fetchAndShaCheck', 'shasum', shasum)
          cb(er, response, shasum)
        })
      }
 
      // validate that the url we just downloaded matches the expected shasum.
      log.silly('fetchAndShaCheck', 'shasum', shasum)
      sha.check(tmp, shasum, function (er) {
        if (er && er.message) {
          // add original filename for better debuggability
          er.message = er.message + '\n' + 'From:     ' + u
        }
        return cb(er, response, shasum)
      })
    })
 
    // 0.8 http streams have a bug, where if they're paused with data in
    // their buffers when the socket closes, they call `end` before emptying
    // those buffers, which results in the entire pipeline ending and thus
    // the point that applied backpressure never being able to trigger a
    // `resume`.
    // We work around this by piping into a pass through stream that has
    // unlimited buffering. The pass through stream is from readable-stream
    // and is thus a current streams3 implementation that is free of these
    // bugs even on 0.8.
    response.pipe(PassThrough({highWaterMark: Infinity})).pipe(tarball)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/cached-package-root.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/cached-package-root.js

Statements: 55.56% (5 / 9)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 55.56% (5 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 1   1   1   1                
var assert = require('assert')
var resolve = require('path').resolve
 
var npm = require('../npm.js')
 
module.exports = getCacheRoot
 
function getCacheRoot (data) {
  assert(data, 'must pass package metadata')
  assert(data.name, 'package metadata must include name')
  assert(data.version, 'package metadata must include version')
 
  return resolve(npm.cache, data.name, data.version)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/caching-client.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/caching-client.js

Statements: 20.51% (24 / 117)      Branches: 0% (0 / 69)      Functions: 0% (0 / 16)      Lines: 21.62% (24 / 111)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 2221   1 1 1 1 1   1 1 1 1 1 1 1 1 1 1   1                   1   1                                                 1                                                                                   1                                                                                                                                               1           1                                 1                                                        
module.exports = CachingRegistryClient
 
var path = require('path')
var fs = require('graceful-fs')
var url = require('url')
var assert = require('assert')
var inherits = require('util').inherits
 
var RegistryClient = require('npm-registry-client')
var npm = require('../npm.js')
var log = require('npmlog')
var getCacheStat = require('./get-stat.js')
var cacheFile = require('npm-cache-filename')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var chownr = require('chownr')
var writeFile = require('write-file-atomic')
var parseJSON = require('../utils/parse-json')
 
function CachingRegistryClient (config) {
  RegistryClient.call(this, adaptConfig(config))
 
  this._mapToCache = cacheFile(config.get('cache'))
 
  // swizzle in our custom cache invalidation logic
  this._request = this.request
  this.request = this._invalidatingRequest
  this.get = get
}
inherits(CachingRegistryClient, RegistryClient)
 
CachingRegistryClient.prototype._invalidatingRequest = function (uri, params, cb) {
  var client = this
  this._request(uri, params, function () {
    var args = arguments
 
    var method = params.method
    if (method !== 'HEAD' && method !== 'GET') {
      var invalidated = client._mapToCache(uri)
      // invalidate cache
      //
      // This is irrelevant for commands that do etag / last-modified caching,
      // but ls and view also have a timed cache, so this keeps the user from
      // thinking that it didn't work when it did.
      // Note that failure is an acceptable option here, since the only
      // result will be a stale cache for some helper commands.
      log.verbose('request', 'invalidating', invalidated, 'on', method)
      return rimraf(invalidated, function () {
        cb.apply(undefined, args)
      })
    }
 
    cb.apply(undefined, args)
  })
}
 
function get (uri, params, cb) {
  assert(typeof uri === 'string', 'must pass registry URI to get')
  assert(params && typeof params === 'object', 'must pass params to get')
  assert(typeof cb === 'function', 'must pass callback to get')
 
  var parsed = url.parse(uri)
  assert(
    parsed.protocol === 'http:' || parsed.protocol === 'https:',
    'must have a URL that starts with http: or https:'
  )
 
  var cacheBase = cacheFile(npm.config.get('cache'))(uri)
  var cachePath = path.join(cacheBase, '.cache.json')
 
  // If the GET is part of a write operation (PUT or DELETE), then
  // skip past the cache entirely, but still save the results.
  if (uri.match(/\?write=true$/)) {
    log.verbose('get', 'GET as part of write; not caching result')
    return get_.call(this, uri, cachePath, params, cb)
  }
 
  if (params.skipCache) {
    return get_.call(this, uri, cachePath, params, cb)
  }
 
  var client = this
  fs.stat(cachePath, function (er, stat) {
    if (!er) {
      fs.readFile(cachePath, function (er, data) {
        data = parseJSON.noExceptions(data)
 
        params.stat = stat
        params.data = data
 
        get_.call(client, uri, cachePath, params, cb)
      })
    } else {
      get_.call(client, uri, cachePath, params, cb)
    }
  })
}
 
function get_ (uri, cachePath, params, cb) {
  var staleOk = params.staleOk === undefined ? false : params.staleOk
  var timeout = params.timeout === undefined ? -1 : params.timeout
  var data = params.data
  var stat = params.stat
  var etag
  var lastModified
 
  timeout = Math.min(timeout, npm.config.get('cache-max') || 0)
  timeout = Math.max(timeout, npm.config.get('cache-min') || -Infinity)
  if (process.env.COMP_CWORD !== undefined &&
      process.env.COMP_LINE !== undefined &&
      process.env.COMP_POINT !== undefined) {
    timeout = Math.max(timeout, 60000)
  }
 
  if (data) {
    if (data._etag) etag = data._etag
    if (data._lastModified) lastModified = data._lastModified
 
    data._cached = true
 
    if (stat && timeout && timeout > 0) {
      if ((Date.now() - stat.mtime.getTime()) / 1000 < timeout) {
        log.verbose('get', uri, 'not expired, no request')
        delete data._etag
        delete data._lastModified
        return cb(null, data, JSON.stringify(data), { statusCode: 304 })
      }
 
      if (staleOk) {
        log.verbose('get', uri, 'staleOk, background update')
        delete data._etag
        delete data._lastModified
        process.nextTick(
          cb.bind(null, null, data, JSON.stringify(data), { statusCode: 304 })
        )
        cb = function () {}
      }
    }
  }
 
  var options = {
    etag: etag,
    lastModified: lastModified,
    follow: params.follow,
    auth: params.auth
  }
  this.request(uri, options, function (er, remoteData, raw, response) {
    // if we get an error talking to the registry, but we have it
    // from the cache, then just pretend we got it.
    if (er && cachePath && data && !data.error) {
      er = null
      response = { statusCode: 304 }
    }
 
    if (response) {
      log.silly('get', 'cb', [response.statusCode, response.headers])
      if (response.statusCode === 304 && (etag || lastModified)) {
        remoteData = data
        log.verbose(etag ? 'etag' : 'lastModified', uri + ' from cache')
      }
    }
 
    data = remoteData
    if (!data) er = er || new Error('failed to fetch from registry: ' + uri)
 
    if (er) return cb(er, data, raw, response)
 
    saveToCache(cachePath, data, saved)
 
    // just give the write the old college try.  if it fails, whatever.
    function saved () {
      delete data._etag
      delete data._lastModified
      cb(er, data, raw, response)
    }
 
    function saveToCache (cachePath, data, saved) {
      log.verbose('get', 'saving', data.name, 'to', cachePath)
      getCacheStat(function (er, st) {
        mkdirp(path.dirname(cachePath), function (er, made) {
          if (er) return saved()
 
          writeFile(cachePath, JSON.stringify(data), function (er) {
            if (er) return saved()
 
            chownr(made || cachePath, st.uid, st.gid, saved)
          })
        })
      })
    }
  })
}
 
function adaptConfig (config) {
  return {
    proxy: {
      http: config.get('proxy'),
      https: config.get('https-proxy'),
      localAddress: config.get('local-address')
    },
    ssl: {
      certificate: config.get('cert'),
      key: config.get('key'),
      ca: config.get('ca'),
      strict: config.get('strict-ssl')
    },
    retry: {
      retries: config.get('fetch-retries'),
      factor: config.get('fetch-retry-factor'),
      minTimeout: config.get('fetch-retry-mintimeout'),
      maxTimeout: config.get('fetch-retry-maxtimeout')
    },
    userAgent: config.get('user-agent'),
    log: log,
    defaultTag: config.get('tag'),
    couchToken: config.get('_token'),
    maxSockets: config.get('maxsockets'),
    scope: npm.projectScope
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/get-stat.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/cache/get-stat.js

Statements: 75% (3 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 75% (3 / 4)      Ignored: none     

1 2 3 4 5 6 7 81 1   1        
var npm = require('../npm.js')
var correctMkdir = require('../utils/correct-mkdir.js')
 
module.exports = function getCacheStat (cb) {
  correctMkdir(npm.cache, cb)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/

Statements: 28% (154 / 550)      Branches: 12.33% (36 / 292)      Functions: 7.69% (6 / 78)      Lines: 29.8% (152 / 510)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/config/
File Statements Branches Functions Lines
clear-credentials-by-uri.js 40% (4 / 10) 0% (0 / 2) 0% (0 / 1) 40% (4 / 10)
cmd-list.js 100% (10 / 10) 50% (1 / 2) 100% (0 / 0) 100% (10 / 10)
core.js 19.26% (52 / 270) 4.32% (6 / 139) 0% (0 / 41) 21.22% (52 / 245)
defaults.js 62.07% (54 / 87) 50.88% (29 / 57) 50% (6 / 12) 65% (52 / 80)
find-prefix.js 19.35% (6 / 31) 0% (0 / 21) 0% (0 / 5) 22.22% (6 / 27)
get-credentials-by-uri.js 10.26% (4 / 39) 0% (0 / 36) 0% (0 / 1) 10.26% (4 / 39)
load-cafile.js 22.22% (4 / 18) 0% (0 / 6) 0% (0 / 4) 25% (4 / 16)
load-prefix.js 17.39% (4 / 23) 0% (0 / 6) 0% (0 / 8) 17.39% (4 / 23)
load-uid.js 50% (3 / 6) 0% (0 / 2) 0% (0 / 1) 50% (3 / 6)
nerf-dart.js 30% (3 / 10) 100% (0 / 0) 0% (0 / 1) 30% (3 / 10)
set-credentials-by-uri.js 15.38% (4 / 26) 0% (0 / 13) 0% (0 / 1) 15.38% (4 / 26)
set-user.js 30% (6 / 20) 0% (0 / 8) 0% (0 / 3) 33.33% (6 / 18)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/clear-credentials-by-uri.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/clear-credentials-by-uri.js

Statements: 40% (4 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 40% (4 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 181   1   1   1                      
var assert = require('assert')
 
var toNerfDart = require('./nerf-dart.js')
 
module.exports = clearCredentialsByURI
 
function clearCredentialsByURI (uri) {
  assert(uri && typeof uri === 'string', 'registry URL is required')
 
  var nerfed = toNerfDart(uri)
 
  this.del(nerfed + ':_authToken', 'user')
  this.del(nerfed + ':_password', 'user')
  this.del(nerfed + ':username', 'user')
  this.del(nerfed + ':email', 'user')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/cmd-list.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/cmd-list.js

Statements: 100% (10 / 10)      Branches: 50% (1 / 2)      Functions: 100% (0 / 0)      Lines: 100% (10 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 1181     1                                     1                                               1                                                                                                                   1             1 1 1 1 1    
var extend = Object.assign || require('util')._extend
 
// short names for common things
var shorthands = {
  'un': 'uninstall',
  'rb': 'rebuild',
  'list': 'ls',
  'ln': 'link',
  'i': 'install',
  'it': 'install-test',
  'up': 'update',
  'c': 'config',
  's': 'search',
  'se': 'search',
  'unstar': 'star', // same function
  'tst': 'test',
  't': 'test',
  'ddp': 'dedupe',
  'v': 'view',
  'run': 'run-script'
}
 
var affordances = {
  'la': 'ls',
  'll': 'ls',
  'verison': 'version',
  'isntall': 'install',
  'dist-tags': 'dist-tag',
  'apihelp': 'help',
  'find-dupes': 'dedupe',
  'upgrade': 'update',
  'login': 'adduser',
  'add-user': 'adduser',
  'author': 'owner',
  'home': 'docs',
  'issues': 'bugs',
  'info': 'view',
  'show': 'view',
  'find': 'search',
  'unlink': 'uninstall',
  'remove': 'uninstall',
  'rm': 'uninstall',
  'r': 'uninstall'
}
 
// these are filenames in .
var cmdList = [
  'install',
  'install-test',
  'uninstall',
  'cache',
  'config',
  'set',
  'get',
  'update',
  'outdated',
  'prune',
  'pack',
  'dedupe',
 
  'rebuild',
  'link',
 
  'publish',
  'star',
  'stars',
  'adduser',
  'login', // This is an alias for `adduser` but it can be confusing
  'logout',
  'unpublish',
  'owner',
  'access',
  'team',
  'deprecate',
  'shrinkwrap',
 
  'help',
  'help-search',
  'ls',
  'search',
  'view',
  'init',
  'version',
  'edit',
  'explore',
  'docs',
  'repo',
  'bugs',
  'root',
  'prefix',
  'bin',
  'whoami',
  'dist-tag',
  'ping',
 
  'test',
  'stop',
  'start',
  'restart',
  'run-script',
  'completion',
  'doctor'
]
 
var plumbing = [
  'build',
  'unbuild',
  'xmas',
  'substack',
  'visnup'
]
module.exports.aliases = extend(extend({}, shorthands), affordances)
module.exports.shorthands = shorthands
module.exports.affordances = affordances
module.exports.cmdList = cmdList
module.exports.plumbing = plumbing
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/core.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/core.js

Statements: 19.26% (52 / 270)      Branches: 4.32% (6 / 139)      Functions: 0% (0 / 41)      Lines: 21.22% (52 / 245)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 4341 1 1 1 1 1 1 1 1 1 1 1 1   1 1 1 1 1 1   1       1       1   1   1     1 1 1                                                                                                                           1                                                                                 1           1                                   1                     1                             1                             1 1                               1 1 1 1 1 1 1 1   1                     1                                                                                                                                       1                               1       1                       1                                   1                                                                                             1                               1                  
var CC = require('config-chain').ConfigChain
var inherits = require('inherits')
var configDefs = require('./defaults.js')
var types = configDefs.types
var once = require('once')
var fs = require('fs')
var path = require('path')
var nopt = require('nopt')
var ini = require('ini')
var Umask = configDefs.Umask
var mkdirp = require('mkdirp')
var umask = require('../utils/umask')
var isWindows = require('../utils/is-windows.js')
 
exports.load = load
exports.Conf = Conf
exports.loaded = false
exports.rootConf = null
exports.usingBuiltin = false
exports.defs = configDefs
 
Object.defineProperty(exports, 'defaults', { get: function () {
  return configDefs.defaults
}, enumerable: true })
 
Object.defineProperty(exports, 'types', { get: function () {
  return configDefs.types
}, enumerable: true })
 
exports.validate = validate
 
var myUid = process.env.SUDO_UID !== undefined
          ? process.env.SUDO_UID : (process.getuid && process.getuid())
var myGid = process.env.SUDO_GID !== undefined
          ? process.env.SUDO_GID : (process.getgid && process.getgid())
 
var loading = false
var loadCbs = []
function load () {
  var cli, builtin, cb
  for (var i = 0; i < arguments.length; i++) {
    switch (typeof arguments[i]) {
      case 'string': builtin = arguments[i]; break
      case 'object': cli = arguments[i]; break
      case 'function': cb = arguments[i]; break
    }
  }
 
  if (!cb) cb = function () {}
 
  if (exports.loaded) {
    var ret = exports.loaded
    if (cli) {
      ret = new Conf(ret)
      ret.unshift(cli)
    }
    return process.nextTick(cb.bind(null, null, ret))
  }
 
  // either a fresh object, or a clone of the passed in obj
  if (!cli) {
    cli = {}
  } else {
    cli = Object.keys(cli).reduce(function (c, k) {
      c[k] = cli[k]
      return c
    }, {})
  }
 
  loadCbs.push(cb)
  if (loading) return
 
  loading = true
 
  cb = once(function (er, conf) {
    if (!er) {
      exports.loaded = conf
      loading = false
    }
    loadCbs.forEach(function (fn) {
      fn(er, conf)
    })
    loadCbs.length = 0
  })
 
  // check for a builtin if provided.
  exports.usingBuiltin = !!builtin
  var rc = exports.rootConf = new Conf()
  if (builtin) {
    rc.addFile(builtin, 'builtin')
  } else {
    rc.add({}, 'builtin')
  }
 
  rc.on('load', function () {
    load_(builtin, rc, cli, cb)
  })
  rc.on('error', cb)
}
 
function load_ (builtin, rc, cli, cb) {
  var defaults = configDefs.defaults
  var conf = new Conf(rc)
 
  conf.usingBuiltin = !!builtin
  conf.add(cli, 'cli')
  conf.addEnv()
 
  conf.loadPrefix(function (er) {
    if (er) return cb(er)
 
    // If you're doing `npm --userconfig=~/foo.npmrc` then you'd expect
    // that ~/.npmrc won't override the stuff in ~/foo.npmrc (or, indeed
    // be used at all).
    //
    // However, if the cwd is ~, then ~/.npmrc is the home for the project
    // config, and will override the userconfig.
    //
    // If you're not setting the userconfig explicitly, then it will be loaded
    // twice, which is harmless but excessive.  If you *are* setting the
    // userconfig explicitly then it will override your explicit intent, and
    // that IS harmful and unexpected.
    //
    // Solution: Do not load project config file that is the same as either
    // the default or resolved userconfig value.  npm will log a "verbose"
    // message about this when it happens, but it is a rare enough edge case
    // that we don't have to be super concerned about it.
    var projectConf = path.resolve(conf.localPrefix, '.npmrc')
    var defaultUserConfig = rc.get('userconfig')
    var resolvedUserConfig = conf.get('userconfig')
    if (!conf.get('global') &&
        projectConf !== defaultUserConfig &&
        projectConf !== resolvedUserConfig) {
      conf.addFile(projectConf, 'project')
      conf.once('load', afterPrefix)
    } else {
      conf.add({}, 'project')
      afterPrefix()
    }
  })
 
  function afterPrefix () {
    conf.addFile(conf.get('userconfig'), 'user')
    conf.once('error', cb)
    conf.once('load', afterUser)
  }
 
  function afterUser () {
    // globalconfig and globalignorefile defaults
    // need to respond to the 'prefix' setting up to this point.
    // Eg, `npm config get globalconfig --prefix ~/local` should
    // return `~/local/etc/npmrc`
    // annoying humans and their expectations!
    if (conf.get('prefix')) {
      var etc = path.resolve(conf.get('prefix'), 'etc')
      mkdirp(etc, function () {
        defaults.globalconfig = path.resolve(etc, 'npmrc')
        defaults.globalignorefile = path.resolve(etc, 'npmignore')
        afterUserContinuation()
      })
    } else {
      afterUserContinuation()
    }
  }
 
  function afterUserContinuation () {
    conf.addFile(conf.get('globalconfig'), 'global')
 
    // move the builtin into the conf stack now.
    conf.root = defaults
    conf.add(rc.shift(), 'builtin')
    conf.once('load', function () {
      conf.loadExtras(afterExtras)
    })
  }
 
  function afterExtras (er) {
    if (er) return cb(er)
 
    // warn about invalid bits.
    validate(conf)
 
    var cafile = conf.get('cafile')
 
    if (cafile) {
      return conf.loadCAFile(cafile, finalize)
    }
 
    finalize()
  }
 
  function finalize (er) {
    if (er) {
      return cb(er)
    }
 
    exports.loaded = conf
    cb(er, conf)
  }
}
 
// Basically the same as CC, but:
// 1. Always ini
// 2. Parses environment variable names in field values
// 3. Field values that start with ~/ are replaced with process.env.HOME
// 4. Can inherit from another Conf object, using it as the base.
inherits(Conf, CC)
function Conf (base) {
  if (!(this instanceof Conf)) return new Conf(base)
 
  CC.call(this)
 
  if (base) {
    if (base instanceof Conf) {
      this.root = base.list[0] || base.root
    } else {
      this.root = base
    }
  } else {
    this.root = configDefs.defaults
  }
}
 
Conf.prototype.loadPrefix = require('./load-prefix.js')
Conf.prototype.loadCAFile = require('./load-cafile.js')
Conf.prototype.loadUid = require('./load-uid.js')
Conf.prototype.setUser = require('./set-user.js')
Conf.prototype.findPrefix = require('./find-prefix.js')
Conf.prototype.getCredentialsByURI = require('./get-credentials-by-uri.js')
Conf.prototype.setCredentialsByURI = require('./set-credentials-by-uri.js')
Conf.prototype.clearCredentialsByURI = require('./clear-credentials-by-uri.js')
 
Conf.prototype.loadExtras = function (cb) {
  this.setUser(function (er) {
    if (er) return cb(er)
    this.loadUid(function (er) {
      if (er) return cb(er)
      // Without prefix, nothing will ever work
      mkdirp(this.prefix, cb)
    }.bind(this))
  }.bind(this))
}
 
Conf.prototype.save = function (where, cb) {
  var target = this.sources[where]
  if (!target || !(target.path || target.source) || !target.data) {
    var er
    if (where !== 'builtin') er = new Error('bad save target: ' + where)
    if (cb) {
      process.nextTick(cb.bind(null, er))
      return this
    }
    return this.emit('error', er)
  }
 
  if (target.source) {
    var pref = target.prefix || ''
    Object.keys(target.data).forEach(function (k) {
      target.source[pref + k] = target.data[k]
    })
    if (cb) process.nextTick(cb)
    return this
  }
 
  var data = ini.stringify(target.data)
 
  var then = function then (er) {
    if (er) return done(er)
 
    fs.chmod(target.path, mode, done)
  }
 
  var done = function done (er) {
    if (er) {
      if (cb) return cb(er)
      else return this.emit('error', er)
    }
    this._saving --
    if (this._saving === 0) {
      if (cb) cb()
      this.emit('save')
    }
  }
 
  then = then.bind(this)
  done = done.bind(this)
  this._saving ++
 
  var mode = where === 'user' ? '0600' : '0666'
  if (!data.trim()) {
    fs.unlink(target.path, function () {
      // ignore the possible error (e.g. the file doesn't exist)
      done(null)
    })
  } else {
    mkdirp(path.dirname(target.path), function (er) {
      if (er) return then(er)
      fs.writeFile(target.path, data, 'utf8', function (er) {
        if (er) return then(er)
        if (where === 'user' && myUid && myGid) {
          fs.chown(target.path, +myUid, +myGid, then)
        } else {
          then()
        }
      })
    })
  }
 
  return this
}
 
Conf.prototype.addFile = function (file, name) {
  name = name || file
  var marker = { __source__: name }
  this.sources[name] = { path: file, type: 'ini' }
  this.push(marker)
  this._await()
  fs.readFile(file, 'utf8', function (er, data) {
    // just ignore missing files.
    if (er) return this.add({}, marker)
 
    this.addString(data, file, 'ini', marker)
  }.bind(this))
  return this
}
 
// always ini files.
Conf.prototype.parse = function (content, file) {
  return CC.prototype.parse.call(this, content, file, 'ini')
}
 
Conf.prototype.add = function (data, marker) {
  try {
    Object.keys(data).forEach(function (k) {
      data[k] = parseField(data[k], k)
    })
  } catch (e) {
    this.emit('error', e)
    return this
  }
  return CC.prototype.add.call(this, data, marker)
}
 
Conf.prototype.addEnv = function (env) {
  env = env || process.env
  var conf = {}
  Object.keys(env)
    .filter(function (k) { return k.match(/^npm_config_/i) })
    .forEach(function (k) {
      if (!env[k]) return
 
      // leave first char untouched, even if
      // it is a '_' - convert all other to '-'
      var p = k.toLowerCase()
               .replace(/^npm_config_/, '')
               .replace(/(?!^)_/g, '-')
      conf[p] = env[k]
    })
  return CC.prototype.addEnv.call(this, '', conf, 'env')
}
 
function parseField (f, k) {
  if (typeof f !== 'string' && !(f instanceof String)) return f
 
  // type can be an array or single thing.
  var typeList = [].concat(types[k])
  var isPath = typeList.indexOf(path) !== -1
  var isBool = typeList.indexOf(Boolean) !== -1
  var isString = typeList.indexOf(String) !== -1
  var isUmask = typeList.indexOf(Umask) !== -1
  var isNumber = typeList.indexOf(Number) !== -1
 
  f = ('' + f).trim()
 
  if (f.match(/^".*"$/)) {
    try {
      f = JSON.parse(f)
    } catch (e) {
      throw new Error('Failed parsing JSON config key ' + k + ': ' + f)
    }
  }
 
  if (isBool && !isString && f === '') return true
 
  switch (f) {
    case 'true': return true
    case 'false': return false
    case 'null': return null
    case 'undefined': return undefined
  }
 
  f = envReplace(f)
 
  if (isPath) {
    var homePattern = isWindows ? /^~(\/|\\)/ : /^~\//
    if (f.match(homePattern) && process.env.HOME) {
      f = path.resolve(process.env.HOME, f.substr(2))
    }
    f = path.resolve(f)
  }
 
  if (isUmask) f = umask.fromString(f)
 
  if (isNumber && !isNaN(f)) f = +f
 
  return f
}
 
function envReplace (f) {
  if (typeof f !== 'string' || !f) return f
 
  // replace any ${ENV} values with the appropriate environ.
  var envExpr = /(\\*)\$\{([^}]+)\}/g
  return f.replace(envExpr, function (orig, esc, name) {
    esc = esc.length && esc.length % 2
    if (esc) return orig
    if (undefined === process.env[name]) {
      throw new Error('Failed to replace env in config: ' + orig)
    }
 
    return process.env[name]
  })
}
 
function validate (cl) {
  // warn about invalid configs at every level.
  cl.list.forEach(function (conf) {
    nopt.clean(conf, configDefs.types)
  })
 
  nopt.clean(cl.root, configDefs.types)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/defaults.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/defaults.js

Statements: 62.07% (54 / 87)      Branches: 50.88% (29 / 57)      Functions: 50% (6 / 12)      Lines: 65% (52 / 80)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401    1 1 1 1 1 1 1 1 1 1   1 1 1               1 1 1       1         1         1 1 1   1                                                     1 1   1   1 1   1   1     1 1 1   1 1 2   1   1         1     1         1                                                                                                                                                                                                                                                       1     1                                                                                                                                                                                                                     1 1       1 1         1 2 2     2     2       1                                                                          
// defaults, types, and shorthands.
 
var path = require('path')
var url = require('url')
var Stream = require('stream').Stream
var semver = require('semver')
var stableFamily = semver.parse(process.version)
var nopt = require('nopt')
var os = require('os')
var osenv = require('osenv')
var umask = require('../utils/umask')
var hasUnicode = require('has-unicode')
 
var log
try {
  log = require('npmlog')
} catch (er) {
  var util = require('util')
  log = { warn: function (m) {
    console.warn(m + ' ' + util.format.apply(util, [].slice.call(arguments, 1)))
  } }
}
 
exports.Umask = Umask
function Umask () {}
function validateUmask (data, k, val) {
  return umask.validate(data, k, val)
}
 
function validateSemver (data, k, val) {
  if (!semver.valid(val)) return false
  data[k] = semver.valid(val)
}
 
function validateStream (data, k, val) {
  if (!(val instanceof Stream)) return false
  data[k] = val
}
 
nopt.typeDefs.semver = { type: semver, validate: validateSemver }
nopt.typeDefs.Stream = { type: Stream, validate: validateStream }
nopt.typeDefs.Umask = { type: Umask, validate: validateUmask }
 
nopt.invalidHandler = function (k, val, type) {
  log.warn('invalid config', k + '=' + JSON.stringify(val))
 
  if (Array.isArray(type)) {
    if (type.indexOf(url) !== -1) type = url
    else if (type.indexOf(path) !== -1) type = path
  }
 
  switch (type) {
    case Umask:
      log.warn('invalid config', 'Must be umask, octal number in range 0000..0777')
      break
    case url:
      log.warn('invalid config', "Must be a full url with 'http://'")
      break
    case path:
      log.warn('invalid config', 'Must be a valid filesystem path')
      break
    case Number:
      log.warn('invalid config', 'Must be a numeric value')
      break
    case Stream:
      log.warn('invalid config', 'Must be an instance of the Stream class')
      break
  }
}
 
Iif (!stableFamily || (+stableFamily.minor % 2)) stableFamily = null
else stableFamily = stableFamily.major + '.' + stableFamily.minor
 
var defaults
 
var temp = osenv.tmpdir()
var home = osenv.home()
 
var uidOrPid = process.getuid ? process.getuid() : process.pid
 
Eif (home) process.env.HOME = home
else home = path.resolve(temp, 'npm-' + uidOrPid)
 
var cacheExtra = process.platform === 'win32' ? 'npm-cache' : '.npm'
var cacheRoot = process.platform === 'win32' && process.env.APPDATA || home
var cache = path.resolve(cacheRoot, cacheExtra)
 
var globalPrefix
Object.defineProperty(exports, 'defaults', {get: function () {
  if (defaults) return defaults
 
  Iif (process.env.PREFIX) {
    globalPrefix = process.env.PREFIX
  } else Iif (process.platform === 'win32') {
    // c:\node\node.exe --> prefix=c:\node\
    globalPrefix = path.dirname(process.execPath)
  } else {
    // /usr/local/bin/node --> prefix=/usr/local
    globalPrefix = path.dirname(path.dirname(process.execPath))
 
    // destdir only is respected on Unix
    Iif (process.env.DESTDIR) {
      globalPrefix = path.join(process.env.DESTDIR, globalPrefix)
    }
  }
 
  defaults = {
    access: null,
    'always-auth': false,
    also: null,
    'auth-type': 'legacy',
 
    'bin-links': true,
    browser: null,
 
    ca: null,
    cafile: null,
 
    cache: cache,
 
    'cache-lock-stale': 60000,
    'cache-lock-retries': 10,
    'cache-lock-wait': 10000,
 
    'cache-max': Infinity,
    'cache-min': 10,
 
    cert: null,
 
    color: true,
    depth: Infinity,
    description: true,
    dev: false,
    'dry-run': false,
    editor: osenv.editor(),
    'engine-strict': false,
    force: false,
 
    'fetch-retries': 2,
    'fetch-retry-factor': 10,
    'fetch-retry-mintimeout': 10000,
    'fetch-retry-maxtimeout': 60000,
 
    git: 'git',
    'git-tag-version': true,
 
    global: false,
    globalconfig: path.resolve(globalPrefix, 'etc', 'npmrc'),
    'global-style': false,
    group: process.platform === 'win32' ? 0
            : process.env.SUDO_GID || (process.getgid && process.getgid()),
    'ham-it-up': false,
    heading: 'npm',
    'if-present': false,
    'ignore-scripts': false,
    'init-module': path.resolve(home, '.npm-init.js'),
    'init-author-name': '',
    'init-author-email': '',
    'init-author-url': '',
    'init-version': '1.0.0',
    'init-license': 'ISC',
    json: false,
    key: null,
    'legacy-bundling': false,
    link: false,
    'local-address': undefined,
    loglevel: 'warn',
    logstream: process.stderr,
    'logs-max': 10,
    long: false,
    maxsockets: 50,
    message: '%s',
    'metrics-registry': null,
    'node-version': process.version,
    'onload-script': false,
    only: null,
    optional: true,
    parseable: false,
    prefix: globalPrefix,
    production: process.env.NODE_ENV === 'production',
    'progress': !process.env.TRAVIS && !process.env.CI,
    'proprietary-attribs': true,
    proxy: null,
    'https-proxy': null,
    'user-agent': 'npm/{npm-version} ' +
                    'node/{node-version} ' +
                    '{platform} ' +
                    '{arch}',
    'rebuild-bundle': true,
    registry: 'https://registry.npmjs.org/',
    rollback: true,
    save: false,
    'save-bundle': false,
    'save-dev': false,
    'save-exact': false,
    'save-optional': false,
    'save-prefix': '^',
    scope: '',
    'scripts-prepend-node-path': 'warn-only',
    searchopts: '',
    searchexclude: null,
    searchlimit: 20,
    searchstaleness: 15 * 60,
    'send-metrics': false,
    shell: osenv.shell(),
    shrinkwrap: true,
    'sign-git-tag': false,
    'sso-poll-frequency': 500,
    'sso-type': 'oauth',
    'strict-ssl': true,
    tag: 'latest',
    'tag-version-prefix': 'v',
    tmp: temp,
    unicode: hasUnicode(),
    'unsafe-perm': process.platform === 'win32' ||
                     process.platform === 'cygwin' ||
                     !(process.getuid && process.setuid &&
                       process.getgid && process.setgid) ||
                     process.getuid() !== 0,
    usage: false,
    user: process.platform === 'win32' ? 0 : 'nobody',
    userconfig: path.resolve(home, '.npmrc'),
    umask: process.umask ? process.umask() : umask.fromString('022'),
    version: false,
    versions: false,
    viewer: process.platform === 'win32' ? 'browser' : 'man',
 
    _exit: true
  }
 
  return defaults
}})
 
exports.types = {
  access: [null, 'restricted', 'public'],
  'always-auth': Boolean,
  also: [null, 'dev', 'development'],
  'auth-type': ['legacy', 'sso', 'saml', 'oauth'],
  'bin-links': Boolean,
  browser: [null, String],
  ca: [null, String, Array],
  cafile: path,
  cache: path,
  'cache-lock-stale': Number,
  'cache-lock-retries': Number,
  'cache-lock-wait': Number,
  'cache-max': Number,
  'cache-min': Number,
  cert: [null, String],
  color: ['always', Boolean],
  depth: Number,
  description: Boolean,
  dev: Boolean,
  'dry-run': Boolean,
  editor: String,
  'engine-strict': Boolean,
  force: Boolean,
  'fetch-retries': Number,
  'fetch-retry-factor': Number,
  'fetch-retry-mintimeout': Number,
  'fetch-retry-maxtimeout': Number,
  git: String,
  'git-tag-version': Boolean,
  global: Boolean,
  globalconfig: path,
  'global-style': Boolean,
  group: [Number, String],
  'https-proxy': [null, url],
  'user-agent': String,
  'ham-it-up': Boolean,
  'heading': String,
  'if-present': Boolean,
  'ignore-scripts': Boolean,
  'init-module': path,
  'init-author-name': String,
  'init-author-email': String,
  'init-author-url': ['', url],
  'init-license': String,
  'init-version': semver,
  json: Boolean,
  key: [null, String],
  'legacy-bundling': Boolean,
  link: Boolean,
  // local-address must be listed as an IP for a local network interface
  // must be IPv4 due to node bug
  'local-address': getLocalAddresses(),
  loglevel: ['silent', 'error', 'warn', 'http', 'info', 'verbose', 'silly'],
  logstream: Stream,
  'logs-max': Number,
  long: Boolean,
  maxsockets: Number,
  message: String,
  'metrics-registry': [null, String],
  'node-version': [null, semver],
  'onload-script': [null, String],
  only: [null, 'dev', 'development', 'prod', 'production'],
  optional: Boolean,
  parseable: Boolean,
  prefix: path,
  production: Boolean,
  progress: Boolean,
  'proprietary-attribs': Boolean,
  proxy: [null, false, url], // allow proxy to be disabled explicitly
  'rebuild-bundle': Boolean,
  registry: [null, url],
  rollback: Boolean,
  save: Boolean,
  'save-bundle': Boolean,
  'save-dev': Boolean,
  'save-exact': Boolean,
  'save-optional': Boolean,
  'save-prefix': String,
  scope: String,
  'scripts-prepend-node-path': [false, true, 'auto', 'warn-only'],
  searchopts: String,
  searchexclude: [null, String],
  searchlimit: Number,
  searchstaleness: Number,
  'send-metrics': Boolean,
  shell: String,
  shrinkwrap: Boolean,
  'sign-git-tag': Boolean,
  'sso-poll-frequency': Number,
  'sso-type': [null, 'oauth', 'saml'],
  'strict-ssl': Boolean,
  tag: String,
  tmp: path,
  unicode: Boolean,
  'unsafe-perm': Boolean,
  usage: Boolean,
  user: [Number, String],
  userconfig: path,
  umask: Umask,
  version: Boolean,
  'tag-version-prefix': String,
  versions: Boolean,
  viewer: String,
  _exit: Boolean
}
 
function getLocalAddresses () {
  var interfaces
  // #8094: some environments require elevated permissions to enumerate
  // interfaces, and synchronously throw EPERM when run without
  // elevated privileges
  try {
    interfaces = os.networkInterfaces()
  } catch (e) {
    interfaces = {}
  }
 
  return Object.keys(interfaces).map(function (nic) {
    return interfaces[nic].filter(function (addr) {
      return addr.family === 'IPv4'
    })
    .map(function (addr) {
      return addr.address
    })
  }).reduce(function (curr, next) {
    return curr.concat(next)
  }, []).concat(undefined)
}
 
exports.shorthands = {
  s: ['--loglevel', 'silent'],
  d: ['--loglevel', 'info'],
  dd: ['--loglevel', 'verbose'],
  ddd: ['--loglevel', 'silly'],
  noreg: ['--no-registry'],
  N: ['--no-registry'],
  reg: ['--registry'],
  'no-reg': ['--no-registry'],
  silent: ['--loglevel', 'silent'],
  verbose: ['--loglevel', 'verbose'],
  quiet: ['--loglevel', 'warn'],
  q: ['--loglevel', 'warn'],
  h: ['--usage'],
  H: ['--usage'],
  '?': ['--usage'],
  help: ['--usage'],
  v: ['--version'],
  f: ['--force'],
  desc: ['--description'],
  'no-desc': ['--no-description'],
  'local': ['--no-global'],
  l: ['--long'],
  m: ['--message'],
  p: ['--parseable'],
  porcelain: ['--parseable'],
  g: ['--global'],
  S: ['--save'],
  D: ['--save-dev'],
  E: ['--save-exact'],
  O: ['--save-optional'],
  y: ['--yes'],
  n: ['--no-yes'],
  B: ['--save-bundle'],
  C: ['--prefix']
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/find-prefix.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/find-prefix.js

Statements: 19.35% (6 / 31)      Branches: 0% (0 / 21)      Functions: 0% (0 / 5)      Lines: 22.22% (6 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58    1   1 1   1 1                                       1                                                          
// try to find the most reasonable prefix to use
 
module.exports = findPrefix
 
var fs = require('fs')
var path = require('path')
 
function findPrefix (p, cb_) {
  function cb (er, p) {
    process.nextTick(function () {
      cb_(er, p)
    })
  }
 
  p = path.resolve(p)
  // if there's no node_modules folder, then
  // walk up until we hopefully find one.
  // if none anywhere, then use cwd.
  var walkedUp = false
  while (path.basename(p) === 'node_modules') {
    p = path.dirname(p)
    walkedUp = true
  }
  if (walkedUp) return cb(null, p)
 
  findPrefix_(p, p, cb)
}
 
function findPrefix_ (p, original, cb) {
  if (p === '/' ||
      (process.platform === 'win32' && p.match(/^[a-zA-Z]:(\\|\/)?$/))) {
    return cb(null, original)
  }
  fs.readdir(p, function (er, files) {
    // an error right away is a bad sign.
    // unless the prefix was simply a non
    // existent directory.
    if (er && p === original) {
      if (er.code === 'ENOENT') return cb(null, original)
      return cb(er)
    }
 
    // walked up too high or something.
    if (er) return cb(null, original)
 
    if (files.indexOf('node_modules') !== -1 ||
        files.indexOf('package.json') !== -1) {
      return cb(null, p)
    }
 
    var d = path.dirname(p)
    if (d === p) return cb(null, original)
 
    return findPrefix_(d, original, cb)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/get-credentials-by-uri.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/get-credentials-by-uri.js

Statements: 10.26% (4 / 39)      Branches: 0% (0 / 36)      Functions: 0% (0 / 1)      Lines: 10.26% (4 / 39)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 761   1   1   1                                                                                                                                          
var assert = require('assert')
 
var toNerfDart = require('./nerf-dart.js')
 
module.exports = getCredentialsByURI
 
function getCredentialsByURI (uri) {
  assert(uri && typeof uri === 'string', 'registry URL is required')
  var nerfed = toNerfDart(uri)
  var defnerf = toNerfDart(this.get('registry'))
 
  // hidden class micro-optimization
  var c = {
    scope: nerfed,
    token: undefined,
    password: undefined,
    username: undefined,
    email: undefined,
    auth: undefined,
    alwaysAuth: undefined
  }
 
  // used to override scope matching for tokens as well as legacy auth
  if (this.get(nerfed + ':always-auth') !== undefined) {
    var val = this.get(nerfed + ':always-auth')
    c.alwaysAuth = val === 'false' ? false : !!val
  } else if (this.get('always-auth') !== undefined) {
    c.alwaysAuth = this.get('always-auth')
  }
 
  if (this.get(nerfed + ':_authToken')) {
    c.token = this.get(nerfed + ':_authToken')
    // the bearer token is enough, don't confuse things
    return c
  }
 
  // Handle the old-style _auth=<base64> style for the default
  // registry, if set.
  //
  // XXX(isaacs): Remove when npm 1.4 is no longer relevant
  var authDef = this.get('_auth')
  var userDef = this.get('username')
  var passDef = this.get('_password')
  if (authDef && !(userDef && passDef)) {
    authDef = new Buffer(authDef, 'base64').toString()
    authDef = authDef.split(':')
    userDef = authDef.shift()
    passDef = authDef.join(':')
  }
 
  if (this.get(nerfed + ':_password')) {
    c.password = new Buffer(this.get(nerfed + ':_password'), 'base64').toString('utf8')
  } else if (nerfed === defnerf && passDef) {
    c.password = passDef
  }
 
  if (this.get(nerfed + ':username')) {
    c.username = this.get(nerfed + ':username')
  } else if (nerfed === defnerf && userDef) {
    c.username = userDef
  }
 
  if (this.get(nerfed + ':email')) {
    c.email = this.get(nerfed + ':email')
  } else if (this.get('email')) {
    c.email = this.get('email')
  }
 
  if (c.username && c.password) {
    c.auth = new Buffer(c.username + ':' + c.password).toString('base64')
  }
 
  return c
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/load-cafile.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/load-cafile.js

Statements: 22.22% (4 / 18)      Branches: 0% (0 / 6)      Functions: 0% (0 / 4)      Lines: 25% (4 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 341   1   1         1                                                
module.exports = loadCAFile
 
var fs = require('fs')
 
function loadCAFile (cafilePath, cb) {
  if (!cafilePath) return process.nextTick(cb)
 
  fs.readFile(cafilePath, 'utf8', afterCARead.bind(this))
 
  function afterCARead (er, cadata) {
    if (er) {
      // previous cafile no longer exists, so just continue on gracefully
      if (er.code === 'ENOENT') return cb()
      return cb(er)
    }
 
    var delim = '-----END CERTIFICATE-----'
    var output
 
    output = cadata
      .split(delim)
      .filter(function (xs) {
        return !!xs.trim()
      })
      .map(function (xs) {
        return xs.trimLeft() + delim
      })
 
    this.set('ca', output)
    cb(null)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/load-prefix.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/load-prefix.js

Statements: 17.39% (4 / 23)      Branches: 0% (0 / 6)      Functions: 0% (0 / 8)      Lines: 17.39% (4 / 23)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 531   1 1   1                                                                                              
module.exports = loadPrefix
 
var findPrefix = require('./find-prefix.js')
var path = require('path')
 
function loadPrefix (cb) {
  var cli = this.list[0]
 
  Object.defineProperty(this, 'prefix',
    {
      set: function (prefix) {
        var g = this.get('global')
        this[g ? 'globalPrefix' : 'localPrefix'] = prefix
      }.bind(this),
      get: function () {
        var g = this.get('global')
        return g ? this.globalPrefix : this.localPrefix
      }.bind(this),
      enumerable: true
    })
 
  Object.defineProperty(this, 'globalPrefix',
    {
      set: function (prefix) {
        this.set('prefix', prefix)
      }.bind(this),
      get: function () {
        return path.resolve(this.get('prefix'))
      }.bind(this),
      enumerable: true
    })
 
  var p
  Object.defineProperty(this, 'localPrefix',
    { set: function (prefix) { p = prefix },
      get: function () { return p },
    enumerable: true })
 
  // try to guess at a good node_modules location.
  // If we are *explicitly* given a prefix on the cli, then
  // always use that.  otherwise, infer local prefix from cwd.
  if (Object.prototype.hasOwnProperty.call(cli, 'prefix')) {
    p = path.resolve(cli.prefix)
    process.nextTick(cb)
  } else {
    findPrefix(process.cwd(), function (er, found) {
      p = found
      cb(er)
    })
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/load-uid.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/load-uid.js

Statements: 50% (3 / 6)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 50% (3 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 171   1       1                    
module.exports = loadUid
 
var getUid = require('uid-number')
 
// Call in the context of a npmconf object
 
function loadUid (cb) {
  // if we're not in unsafe-perm mode, then figure out who
  // to run stuff as.  Do this first, to support `npm update npm -g`
  if (!this.get('unsafe-perm')) {
    getUid(this.get('user'), this.get('group'), cb)
  } else {
    process.nextTick(cb)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/nerf-dart.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/nerf-dart.js

Statements: 30% (3 / 10)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 30% (3 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 251   1                     1                      
var url = require('url')
 
module.exports = toNerfDart
 
/**
 * Maps a URL to an identifier.
 *
 * Name courtesy schiffertronix media LLC, a New Jersey corporation
 *
 * @param {String} uri The URL to be nerfed.
 *
 * @returns {String} A nerfed URL.
 */
function toNerfDart (uri) {
  var parsed = url.parse(uri)
  delete parsed.protocol
  delete parsed.auth
  delete parsed.query
  delete parsed.search
  delete parsed.hash
 
  return url.resolve(url.format(parsed), '.')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/set-credentials-by-uri.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/set-credentials-by-uri.js

Statements: 15.38% (4 / 26)      Branches: 0% (0 / 13)      Functions: 0% (0 / 1)      Lines: 15.38% (4 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411   1   1   1                                                                    
var assert = require('assert')
 
var toNerfDart = require('./nerf-dart.js')
 
module.exports = setCredentialsByURI
 
function setCredentialsByURI (uri, c) {
  assert(uri && typeof uri === 'string', 'registry URL is required')
  assert(c && typeof c === 'object', 'credentials are required')
 
  var nerfed = toNerfDart(uri)
 
  if (c.token) {
    this.set(nerfed + ':_authToken', c.token, 'user')
    this.del(nerfed + ':_password', 'user')
    this.del(nerfed + ':username', 'user')
    this.del(nerfed + ':email', 'user')
    this.del(nerfed + ':always-auth', 'user')
  } else if (c.username || c.password || c.email) {
    assert(c.username, 'must include username')
    assert(c.password, 'must include password')
    assert(c.email, 'must include email address')
 
    this.del(nerfed + ':_authToken', 'user')
 
    var encoded = new Buffer(c.password, 'utf8').toString('base64')
    this.set(nerfed + ':_password', encoded, 'user')
    this.set(nerfed + ':username', c.username, 'user')
    this.set(nerfed + ':email', c.email, 'user')
 
    if (c.alwaysAuth !== undefined) {
      this.set(nerfed + ':always-auth', c.alwaysAuth, 'user')
    } else {
      this.del(nerfed + ':always-auth', 'user')
    }
  } else {
    throw new Error('No credentials to set.')
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/set-user.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/config/set-user.js

Statements: 30% (6 / 20)      Branches: 0% (0 / 8)      Functions: 0% (0 / 3)      Lines: 33.33% (6 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 311   1 1 1 1   1                                              
module.exports = setUser
 
var assert = require('assert')
var path = require('path')
var fs = require('fs')
var mkdirp = require('mkdirp')
 
function setUser (cb) {
  var defaultConf = this.root
  assert(defaultConf !== Object.prototype)
 
  // If global, leave it as-is.
  // If not global, then set the user to the owner of the prefix folder.
  // Just set the default, so it can be overridden.
  if (this.get('global')) return cb()
  if (process.env.SUDO_UID) {
    defaultConf.user = +(process.env.SUDO_UID)
    return cb()
  }
 
  var prefix = path.resolve(this.get('prefix'))
  mkdirp(prefix, function (er) {
    if (er) return cb(er)
    fs.stat(prefix, function (er, st) {
      defaultConf.user = st && st.uid
      return cb(er)
    })
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/

Statements: 26.39% (38 / 144)      Branches: 0% (0 / 45)      Functions: 0% (0 / 25)      Lines: 28.79% (38 / 132)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/doctor/
File Statements Branches Functions Lines
check-files-permission.js 22% (11 / 50) 0% (0 / 24) 0% (0 / 7) 25% (11 / 44)
check-ping.js 44.44% (4 / 9) 100% (0 / 0) 0% (0 / 2) 44.44% (4 / 9)
checksum-cached-files.js 25.53% (12 / 47) 0% (0 / 11) 0% (0 / 9) 27.91% (12 / 43)
get-git-path.js 44.44% (4 / 9) 100% (0 / 0) 0% (0 / 2) 44.44% (4 / 9)
get-latest-nodejs-version.js 20% (4 / 20) 0% (0 / 10) 0% (0 / 3) 22.22% (4 / 18)
get-latest-npm-version.js 33.33% (3 / 9) 100% (0 / 0) 0% (0 / 2) 33.33% (3 / 9)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/check-files-permission.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/check-files-permission.js

Statements: 22% (11 / 50)      Branches: 0% (0 / 24)      Functions: 0% (0 / 7)      Lines: 25% (11 / 44)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571 1 1 1 1 1 1   1                                           1     1                                         1    
var fs = require('fs')
var path = require('path')
var getUid = require('uid-number')
var chain = require('slide').chain
var log = require('npmlog')
var npm = require('../npm.js')
var fileCompletion = require('../utils/completion/file-completion.js')
 
function checkFilesPermission (root, mask, cb) {
  if (process.platform === 'win32') return cb(null, true)
  getUid(npm.config.get('user'), npm.config.get('group'), function (e, uid, gid) {
    if (e) {
      tracker.finish()
      tracker.warn('checkFilePermissions', 'Error looking up user and group:', e)
      return cb(e)
    }
    var tracker = log.newItem('checkFilePermissions', 1)
    tracker.info('checkFilePermissions', 'Building file list of ' + root)
    fileCompletion(root, '.', Infinity, function (e, files) {
      if (e) {
        tracker.warn('checkFilePermissions', 'Error building file list:', e)
        tracker.finish()
        return cb(e)
      }
      tracker.addWork(files.length)
      tracker.completeWork(1)
      chain(files.map(andCheckFile), function (er) {
        tracker.finish()
        cb(null, !er)
      })
      function andCheckFile (f) {
        return [checkFile, f]
      }
      function checkFile (f, next) {
        var file = path.join(root, f)
        tracker.silly('checkFilePermissions', f)
        fs.lstat(file, function (e, stat) {
          tracker.completeWork(1)
          if (e) return next(e)
          if (!stat.isFile()) return next()
          var mode = stat.mode
          var isGroup = stat.gid ? stat.gid === gid : true
          var isUser = stat.uid ? stat.uid === uid : true
          if ((mode & parseInt('000' + mask, 8))) return next()
          if ((isGroup && mode & parseInt('00' + mask + '0', 8))) return next()
          if ((isUser && mode & parseInt('0' + mask + '00', 8))) return next()
          tracker.error('checkFilePermissions', 'Missing permissions on (' + isGroup + ', ' + isUser + ', ' + mode + ')', file)
          return next(new Error('Missing permissions for ' + file))
        })
      }
    })
  })
}
 
module.exports = checkFilesPermission
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/check-ping.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/check-ping.js

Statements: 44.44% (4 / 9)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 44.44% (4 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 151 1   1                 1    
var log = require('npmlog')
var ping = require('../ping.js')
 
function checkPing (cb) {
  var tracker = log.newItem('checkPing', 1)
  tracker.info('checkPing', 'Pinging registry')
  ping({}, true, function (err, pong) {
    tracker.finish()
    cb(err, pong)
  })
}
 
module.exports = checkPing
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/checksum-cached-files.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/checksum-cached-files.js

Statements: 25.53% (12 / 47)      Branches: 0% (0 / 11)      Functions: 0% (0 / 9)      Lines: 27.91% (12 / 43)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 641 1 1 1 1 1 1   1             1                           1     1                                                         1    
var crypto = require('crypto')
var fs = require('fs')
var path = require('path')
var chain = require('slide').chain
var log = require('npmlog')
var npm = require('../npm')
var fileCompletion = require('../utils/completion/file-completion.js')
 
function checksum (str) {
  return crypto
    .createHash('sha1')
    .update(str, 'utf8')
    .digest('hex')
}
 
function checksumCachedFiles (cb) {
  var tracker = log.newItem('checksumCachedFiles', 1)
  tracker.info('checksumCachedFiles', 'Building file list of ' + npm.cache)
  fileCompletion(npm.cache, '.', Infinity, function (e, files) {
    if (e) {
      tracker.finish()
      return cb(e)
    }
    tracker.addWork(files.length)
    tracker.completeWork(1)
    chain(files.map(andChecksumFile), function (er) {
      tracker.finish()
      cb(null, !er)
    })
    function andChecksumFile (f) {
      return [function (next) { process.nextTick(function () { checksumFile(f, next) }) }]
    }
    function checksumFile (f, next) {
      var file = path.join(npm.cache, f)
      tracker.silly('checksumFile', f)
      if (!/.tgz$/.test(file)) {
        tracker.completeWork(1)
        return next()
      }
      fs.readFile(file, function (err, tgz) {
        tracker.completeWork(1)
        if (err) return next(err)
        try {
          var pkgJSON = fs.readFileSync(path.join(path.dirname(file), 'package/package.json'))
        } catch (e) {
          return next() // no package.json in cche is ok
        }
        try {
          var pkg = JSON.parse(pkgJSON)
          var shasum = (pkg.dist && pkg.dist.shasum) || pkg._shasum
          var actual = checksum(tgz)
          if (actual !== shasum) return next(new Error('Checksum mismatch on ' + file + ', expected: ' + shasum + ', got: ' + shasum))
          return next()
        } catch (e) {
          return next(new Error('Error parsing JSON in ' + file + ': ' + e))
        }
      })
    }
  })
}
 
module.exports = checksumCachedFiles
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/get-git-path.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/get-git-path.js

Statements: 44.44% (4 / 9)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 44.44% (4 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 151 1   1                 1    
var log = require('npmlog')
var which = require('which')
 
function getGitPath (cb) {
  var tracker = log.newItem('getGitPath', 1)
  tracker.info('getGitPath', 'Finding git in your PATH')
  which('git', function (err, path) {
    tracker.finish()
    cb(err, path)
  })
}
 
module.exports = getGitPath
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/get-latest-nodejs-version.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/get-latest-nodejs-version.js

Statements: 20% (4 / 20)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 22.22% (4 / 18)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/doctor/ » get-latest-nodejs-version.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 281 1   1                                           1    
var log = require('npmlog')
var request = require('request')
 
function getLatestNodejsVersion (url, cb) {
  var tracker = log.newItem('getLatestNodejsVersion', 1)
  tracker.info('getLatestNodejsVersion', 'Getting Node.js release information')
  var version = ''
  url = url || 'https://nodejs.org/dist/index.json'
  request(url, function (e, res, index) {
    tracker.finish()
    if (e) return cb(e)
    if (res.statusCode !== 200) {
      return cb(new Error('Status not 200, ' + res.statusCode))
    }
    try {
      JSON.parse(index).forEach(function (item) {
        if (item.lts && item.version > version) version = item.version
      })
      cb(null, version)
    } catch (e) {
      cb(e)
    }
  })
}
 
module.exports = getLatestNodejsVersion
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/get-latest-npm-version.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/doctor/get-latest-npm-version.js

Statements: 33.33% (3 / 9)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 33.33% (3 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 152 2   1                      
var log = require('npmlog')
var fetchPackageMetadata = require('../fetch-package-metadata')
 
function getLatestNpmVersion (cb) {
  var tracker = log.newItem('getLatestNpmVersion', 1)
  tracker.info('getLatestNpmVersion', 'Getting npm package information')
  fetchPackageMetadata('npm@latest', '.', {fullMetadata: true}, function (e, d) {
    tracker.finish()
    cb(e, d.version)
  })
}
 
module.exports = getLatestNpmVersion
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/

Statements: 11.37% (72 / 633)      Branches: 0% (0 / 380)      Functions: 0% (0 / 121)      Lines: 13.24% (72 / 544)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/install/
File Statements Branches Functions Lines
deps.js 8.65% (41 / 474) 0% (0 / 300) 0% (0 / 91) 10.3% (41 / 398)
flatten-tree.js 23.53% (8 / 34) 0% (0 / 10) 0% (0 / 3) 25.81% (8 / 31)
is-extraneous.js 24% (6 / 25) 0% (0 / 19) 0% (0 / 6) 26.09% (6 / 23)
is-registry-specifier.js 66.67% (2 / 3) 0% (0 / 3) 0% (0 / 1) 66.67% (2 / 3)
mutate-into-logical-tree.js 12.2% (10 / 82) 0% (0 / 40) 0% (0 / 16) 13.51% (10 / 74)
realize-shrinkwrap-specifier.js 33.33% (5 / 15) 0% (0 / 8) 0% (0 / 4) 33.33% (5 / 15)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/deps.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/deps.js

Statements: 8.65% (41 / 474)      Branches: 0% (0 / 300)      Functions: 0% (0 / 91)      Lines: 10.3% (41 / 398)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665  18 18 18 18 18 18 18 18 18 18 18 18 18 18                                             1                                       1                                                                           1                             1                 1                                         1                                                                           1                       1                                     1           1             1           1                                                                                                                 1       1                                           1                                         1                                                                                 1                                   1                                                                           1                                         1                                         1                                   1             1             1                             1                                                                                                                       1                                                                                     1                                                                                      
'use strict'
var assert = require('assert')
var path = require('path')
var semver = require('semver')
var asyncMap = require('slide').asyncMap
var chain = require('slide').chain
var union = require('lodash.union')
var iferr = require('iferr')
var npa = require('npm-package-arg')
var validate = require('aproba')
var realizePackageSpecifier = require('realize-package-specifier')
var realizeShrinkwrapSpecifier = require('./realize-shrinkwrap-specifier')
var asap = require('asap')
var dezalgo = require('dezalgo')
var fetchPackageMetadata = require('../fetch-package-metadata.js')
var andAddParentToErrors = require('./and-add-parent-to-errors.js')
var addShrinkwrap = require('../fetch-package-metadata.js').addShrinkwrap
var addBundled = require('../fetch-package-metadata.js').addBundled
var readShrinkwrap = require('./read-shrinkwrap.js')
var inflateShrinkwrap = require('./inflate-shrinkwrap.js')
var inflateBundled = require('./inflate-bundled.js')
var andFinishTracker = require('./and-finish-tracker.js')
var npm = require('../npm.js')
var flatNameFromTree = require('./flatten-tree.js').flatNameFromTree
var createChild = require('./node.js').create
var resetMetadata = require('./node.js').reset
var andIgnoreErrors = require('./and-ignore-errors.js')
var isInstallable = require('./validate-args.js').isInstallable
var packageId = require('../utils/package-id.js')
var moduleName = require('../utils/module-name.js')
var isDevDep = require('./is-dev-dep.js')
var isProdDep = require('./is-prod-dep.js')
var reportOptionalFailure = require('./report-optional-failure.js')
 
// The export functions in this module mutate a dependency tree, adding
// items to them.
 
function isDep (tree, child, cb) {
  var name = moduleName(child)
  var prodVer = isProdDep(tree, name)
  var devVer = isDevDep(tree, name)
 
  childDependencySpecifier(tree, name, prodVer, function (er, prodSpec) {
    if (er) return cb(child.fromShrinkwrap)
    var matches
    if (prodSpec) matches = doesChildVersionMatch(child, prodSpec, tree)
    if (matches) return cb(true, prodSpec)
    if (devVer === prodVer) return cb(child.fromShrinkwrap)
    childDependencySpecifier(tree, name, devVer, function (er, devSpec) {
      if (er) return cb(child.fromShrinkwrap)
      cb(doesChildVersionMatch(child, devSpec, tree) || child.fromShrinkwrap, null, devSpec)
    })
  })
}
 
var registryTypes = { range: true, version: true }
 
function doesChildVersionMatch (child, requested, requestor) {
  // we always consider deps provided by a shrinkwrap as "correct" or else
  // we'll subvert them if they're intentionally "invalid"
  if (child.parent === requestor && child.fromShrinkwrap) return true
  // ranges of * ALWAYS count as a match, because when downloading we allow
  // prereleases to match * if there are ONLY prereleases
  if (requested.spec === '*') return true
 
  var childReq = child.package._requested
  if (!childReq) childReq = npa(moduleName(child) + '@' + child.package._from)
  if (childReq) {
    if (childReq.rawSpec === requested.rawSpec) return true
    if (childReq.type === requested.type && childReq.spec === requested.spec) return true
  }
  // If _requested didn't exist OR if it didn't match then we'll try using
  // _from. We pass it through npa to normalize the specifier.
  // This can happen when installing from an `npm-shrinkwrap.json` where `_requested` will
  // be the tarball URL from `resolved` and thus can't match what's in the `package.json`.
  // In those cases _from, will be preserved and we can compare that to ensure that they
  // really came from the same sources.
  // You'll see this scenario happen with at least tags and git dependencies.
  if (!registryTypes[requested.type]) {
    if (child.package._from) {
      var fromReq = npa(child.package._from)
      if (fromReq.rawSpec === requested.rawSpec) return true
      if (fromReq.type === requested.type && fromReq.spec === requested.spec) return true
    }
    return false
  }
  return semver.satisfies(child.package.version, requested.spec)
}
 
// TODO: Rename to maybe computeMetadata or computeRelationships
exports.recalculateMetadata = function (tree, log, next) {
  recalculateMetadata(tree, log, {}, next)
}
 
exports._childDependencySpecifier = childDependencySpecifier
function childDependencySpecifier (tree, name, spec, cb) {
  if (!tree.resolved) tree.resolved = {}
  if (!tree.resolved[name]) tree.resolved[name] = {}
  if (tree.resolved[name][spec]) {
    return asap(function () {
      cb(null, tree.resolved[name][spec])
    })
  }
  realizePackageSpecifier(name + '@' + spec, packageRelativePath(tree), function (er, req) {
    if (er) return cb(er)
    tree.resolved[name][spec] = req
    cb(null, req)
  })
}
 
function recalculateMetadata (tree, log, seen, next) {
  validate('OOOF', arguments)
  if (seen[tree.path]) return next()
  seen[tree.path] = true
  if (tree.parent == null) {
    resetMetadata(tree)
    tree.isTop = true
  }
 
  function markDeps (toMark, done) {
    var name = toMark.name
    var spec = toMark.spec
    var kind = toMark.kind
    childDependencySpecifier(tree, name, spec, function (er, req) {
      if (er || !req.name) return done()
      var child = findRequirement(tree, req.name, req)
      if (child) {
        resolveWithExistingModule(child, tree, log, andIgnoreErrors(done))
      } else if (kind === 'dep') {
        tree.missingDeps[req.name] = req.rawSpec
        done()
      } else if (kind === 'dev') {
        tree.missingDevDeps[req.name] = req.rawSpec
        done()
      } else {
        done()
      }
    })
  }
 
  function makeMarkable (deps, kind) {
    if (!deps) return []
    return Object.keys(deps).map(function (depname) { return { name: depname, spec: deps[depname], kind: kind } })
  }
 
  // Ensure dependencies and dev dependencies are marked as required
  var tomark = makeMarkable(tree.package.dependencies, 'dep')
  if (tree.isTop) tomark = union(tomark, makeMarkable(tree.package.devDependencies, 'dev'))
 
  // Ensure any children ONLY from a shrinkwrap are also included
  var childrenOnlyInShrinkwrap = tree.children.filter(function (child) {
    return child.fromShrinkwrap &&
      !tree.package.dependencies[child.package.name] &&
      !tree.package.devDependencies[child.package.name]
  })
  var tomarkOnlyInShrinkwrap = childrenOnlyInShrinkwrap.map(function (child) {
    var name = child.package.name
    var matched = child.package._spec.match(/^@?[^@]+@(.*)$/)
    var spec = matched ? matched[1] : child.package._spec
    var kind = tree.package.dependencies[name] ? 'dep'
             : tree.package.devDependencies[name] ? 'dev'
             : 'dep'
    return { name: name, spec: spec, kind: kind }
  })
  tomark = union(tomark, tomarkOnlyInShrinkwrap)
 
  // Don't bother trying to recalc children of failed deps
  tree.children = tree.children.filter(function (child) { return !child.failed })
 
  chain([
    [asyncMap, tomark, markDeps],
    [asyncMap, tree.children, function (child, done) { recalculateMetadata(child, log, seen, done) }]
  ], function () {
    tree.location = flatNameFromTree(tree)
    next(null, tree)
  })
}
 
function addRequiredDep (tree, child, cb) {
  isDep(tree, child, function (childIsDep, childIsProdDep, childIsDevDep) {
    if (!childIsDep) return cb(false)
    replaceModuleByPath(child, 'requiredBy', tree)
    replaceModuleByName(tree, 'requires', child)
    if (childIsProdDep && tree.missingDeps) delete tree.missingDeps[moduleName(child)]
    if (childIsDevDep && tree.missingDevDeps) delete tree.missingDevDeps[moduleName(child)]
    cb(true)
  })
}
 
exports.removeObsoleteDep = removeObsoleteDep
function removeObsoleteDep (child, log) {
  if (child.removed) return
  child.removed = true
  if (log) {
    log.silly('removeObsoleteDep', 'removing ' + packageId(child) +
      ' from the tree as its been replaced by a newer version or is no longer required')
  }
  // remove from physical tree
  if (child.parent) {
    child.parent.children = child.parent.children.filter(function (pchild) { return pchild !== child })
  }
  // remove from logical tree
  var requires = child.requires || []
  requires.forEach(function (requirement) {
    requirement.requiredBy = requirement.requiredBy.filter(function (reqBy) { return reqBy !== child })
    if (requirement.requiredBy.length === 0) removeObsoleteDep(requirement, log)
  })
}
 
function matchingDep (tree, name) {
  if (tree.package.dependencies && tree.package.dependencies[name]) return tree.package.dependencies[name]
  if (tree.package.devDependencies && tree.package.devDependencies[name]) return tree.package.devDependencies[name]
  return
}
 
function packageRelativePath (tree) {
  if (!tree) return ''
  var requested = tree.package._requested || {}
  var isLocal = requested.type === 'directory' || requested.type === 'local'
  return isLocal ? requested.spec : tree.path
}
 
function getShrinkwrap (tree, name) {
  return tree.package._shrinkwrap && tree.package._shrinkwrap.dependencies && tree.package._shrinkwrap.dependencies[name]
}
 
exports.getAllMetadata = function (args, tree, where, next) {
  asyncMap(args, function (arg, done) {
    function fetchMetadataWithVersion () {
      var version = matchingDep(tree, arg)
      var spec = version == null ? arg : arg + '@' + version
      return fetchPackageMetadata(spec, where, done)
    }
    if (tree && arg.lastIndexOf('@') <= 0) {
      var sw = getShrinkwrap(tree, arg)
      if (sw) {
        return realizeShrinkwrapSpecifier(arg, sw, where, function (err, spec) {
          if (err) {
            return fetchMetadataWithVersion()
          } else {
            return fetchPackageMetadata(spec, where, done)
          }
        })
      } else {
        return fetchMetadataWithVersion()
      }
    } else {
      return fetchPackageMetadata(arg, where, done)
    }
  }, next)
}
 
// Add a list of args to tree's top level dependencies
exports.loadRequestedDeps = function (args, tree, saveToDependencies, log, next) {
  validate('AOOF', [args, tree, log, next])
  asyncMap(args, function (pkg, done) {
    var depLoaded = andAddParentToErrors(tree, done)
    resolveWithNewModule(pkg, tree, log.newGroup('loadRequestedDeps'), iferr(depLoaded, function (child, tracker) {
      validate('OO', arguments)
      if (npm.config.get('global')) {
        child.isGlobal = true
      }
      var childName = moduleName(child)
      if (saveToDependencies) {
        tree.package[saveToDependencies][childName] =
          child.package._requested.rawSpec || child.package._requested.spec
      }
      if (saveToDependencies && saveToDependencies !== 'devDependencies') {
        tree.package.dependencies[childName] =
          child.package._requested.rawSpec || child.package._requested.spec
      }
      child.userRequired = true
      child.save = saveToDependencies
 
      // For things the user asked to install, that aren't a dependency (or
      // won't be when we're done), flag it as "depending" on the user
      // themselves, so we don't remove it as a dep that no longer exists
      addRequiredDep(tree, child, function (childIsDep) {
        if (!childIsDep) child.userRequired = true
        depLoaded(null, child, tracker)
      })
    }))
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}
 
function moduleNameMatches (name) {
  return function (child) { return moduleName(child) === name }
}
 
function noModuleNameMatches (name) {
  return function (child) { return moduleName(child) !== name }
}
 
// while this implementation does not require async calling, doing so
// gives this a consistent interface with loadDeps et al
exports.removeDeps = function (args, tree, saveToDependencies, log, next) {
  validate('AOOF', [args, tree, log, next])
  args.forEach(function (pkg) {
    var pkgName = moduleName(pkg)
    var toRemove = tree.children.filter(moduleNameMatches(pkgName))
    var pkgToRemove = toRemove[0] || createChild({package: {name: pkgName}})
    if (saveToDependencies) {
      replaceModuleByPath(tree, 'removed', pkgToRemove)
      pkgToRemove.save = saveToDependencies
    }
    removeObsoleteDep(pkgToRemove)
  })
  log.finish()
  next()
}
 
function andForEachChild (load, next) {
  validate('F', [next])
  next = dezalgo(next)
  return function (er, children, logs) {
    // when children is empty, logs won't be passed in at all (asyncMap is weird)
    // so shortcircuit before arg validation
    if (!er && (!children || children.length === 0)) return next()
    validate('EAA', arguments)
    if (er) return next(er)
    assert(children.length === logs.length)
    var cmds = []
    for (var ii = 0; ii < children.length; ++ii) {
      cmds.push([load, children[ii], logs[ii]])
    }
    var sortedCmds = cmds.sort(function installOrder (aa, bb) {
      return moduleName(aa[1]).localeCompare(moduleName(bb[1]))
    })
    chain(sortedCmds, next)
  }
}
 
function isDepOptional (tree, name, pkg) {
  if (pkg.package && pkg.package._optional) return true
  if (!tree.package.optionalDependencies) return false
  if (tree.package.optionalDependencies[name] != null) return true
  return false
}
 
var failedDependency = exports.failedDependency = function (tree, name_pkg) {
  var name
  var pkg = {}
  if (typeof name_pkg === 'string') {
    name = name_pkg
  } else {
    pkg = name_pkg
    name = moduleName(pkg)
  }
  tree.children = tree.children.filter(noModuleNameMatches(name))
 
  if (isDepOptional(tree, name, pkg)) {
    return false
  }
 
  tree.failed = true
 
  if (tree.isTop) return true
 
  if (tree.userRequired) return true
 
  removeObsoleteDep(tree)
 
  if (!tree.requiredBy) return false
 
  for (var ii = 0; ii < tree.requiredBy.length; ++ii) {
    var requireParent = tree.requiredBy[ii]
    if (failedDependency(requireParent, tree.package)) {
      return true
    }
  }
  return false
}
 
function andHandleOptionalErrors (log, tree, name, done) {
  validate('OOSF', arguments)
  return function (er, child, childLog) {
    if (!er) validate('OO', [child, childLog])
    if (!er) return done(er, child, childLog)
    var isFatal = failedDependency(tree, name)
    if (er && !isFatal) {
      tree.children = tree.children.filter(noModuleNameMatches(name))
      reportOptionalFailure(tree, name, er)
      return done()
    } else {
      return done(er, child, childLog)
    }
  }
}
 
// Load any missing dependencies in the given tree
exports.loadDeps = loadDeps
function loadDeps (tree, log, next) {
  validate('OOF', arguments)
  if (tree.loaded || (tree.parent && tree.parent.failed) || tree.removed) return andFinishTracker.now(log, next)
  if (tree.parent) tree.loaded = true
  if (!tree.package.dependencies) tree.package.dependencies = {}
  asyncMap(Object.keys(tree.package.dependencies), function (dep, done) {
    var version = tree.package.dependencies[dep]
    if (tree.package.optionalDependencies &&
        tree.package.optionalDependencies[dep] &&
        !npm.config.get('optional')) {
      return done()
    }
 
    addDependency(dep, version, tree, log.newGroup('loadDep:' + dep), andHandleOptionalErrors(log, tree, dep, done))
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}
 
// Load development dependencies into the given tree
exports.loadDevDeps = function (tree, log, next) {
  validate('OOF', arguments)
  if (!tree.package.devDependencies) return andFinishTracker.now(log, next)
  // if any of our prexisting children are from a shrinkwrap then we skip
  // loading dev deps as the shrinkwrap will already have provided them for us.
  if (tree.children.some(function (child) { return child.shrinkwrapDev })) {
    return andFinishTracker.now(log, next)
  }
  asyncMap(Object.keys(tree.package.devDependencies), function (dep, done) {
    // things defined as both dev dependencies and regular dependencies are treated
    // as the former
    if (tree.package.dependencies[dep]) return done()
 
    var logGroup = log.newGroup('loadDevDep:' + dep)
    addDependency(dep, tree.package.devDependencies[dep], tree, logGroup, done)
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}
 
var loadExtraneous = exports.loadExtraneous = function (tree, log, next) {
  var seen = {}
  function loadExtraneous (tree, log, next) {
    validate('OOF', arguments)
    if (seen[tree.path]) return next()
    seen[tree.path] = true
    asyncMap(tree.children.filter(function (child) { return !child.loaded }), function (child, done) {
      resolveWithExistingModule(child, tree, log, done)
    }, andForEachChild(loadExtraneous, andFinishTracker(log, next)))
  }
  loadExtraneous(tree, log, next)
}
 
exports.loadExtraneous.andResolveDeps = function (tree, log, next) {
  validate('OOF', arguments)
  // For canonicalized trees (eg from shrinkwrap) we don't want to bother
  // resolving the dependencies of extraneous deps.
  if (tree.loaded) return loadExtraneous(tree, log, next)
  asyncMap(tree.children.filter(function (child) { return !child.loaded }), function (child, done) {
    resolveWithExistingModule(child, tree, log, done)
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}
 
function addDependency (name, versionSpec, tree, log, done) {
  validate('SSOOF', arguments)
  var next = andAddParentToErrors(tree, done)
  childDependencySpecifier(tree, name, versionSpec, iferr(done, function (req) {
    var child = findRequirement(tree, name, req)
    if (child) {
      resolveWithExistingModule(child, tree, log, iferr(next, function (child, log) {
        if (child.package._shrinkwrap === undefined) {
          readShrinkwrap.andInflate(child, function (er) { next(er, child, log) })
        } else {
          next(null, child, log)
        }
      }))
    } else {
      fetchPackageMetadata(req, packageRelativePath(tree), {tracker: log.newItem('fetchMetadata')}, iferr(next, function (pkg) {
        resolveWithNewModule(pkg, tree, log, next)
      }))
    }
  }))
}
 
function resolveWithExistingModule (child, tree, log, next) {
  validate('OOOF', arguments)
  addRequiredDep(tree, child, function () {
    if (tree.parent && child.parent !== tree) updatePhantomChildren(tree.parent, child)
    next(null, child, log)
  })
}
 
var updatePhantomChildren = exports.updatePhantomChildren = function (current, child) {
  validate('OO', arguments)
  while (current && current !== child.parent) {
    if (!current.phantomChildren) current.phantomChildren = {}
    current.phantomChildren[moduleName(child)] = child
    current = current.parent
  }
}
 
exports._replaceModuleByPath = replaceModuleByPath
function replaceModuleByPath (obj, key, child) {
  return replaceModule(obj, key, child, function (replacing, child) {
    return replacing.path === child.path
  })
}
 
exports._replaceModuleByName = replaceModuleByName
function replaceModuleByName (obj, key, child) {
  var childName = moduleName(child)
  return replaceModule(obj, key, child, function (replacing, child) {
    return moduleName(replacing) === childName
  })
}
 
function replaceModule (obj, key, child, matchBy) {
  validate('OSOF', arguments)
  if (!obj[key]) obj[key] = []
  // we replace children with a new array object instead of mutating it
  // because mutating it results in weird failure states.
  // I would very much like to know _why_ this is. =/
  var children = [].concat(obj[key])
  for (var replaceAt = 0; replaceAt < children.length; ++replaceAt) {
    if (matchBy(children[replaceAt], child)) break
  }
  var replacing = children.splice(replaceAt, 1, child)
  obj[key] = children
  return replacing[0]
}
 
function resolveWithNewModule (pkg, tree, log, next) {
  validate('OOOF', arguments)
 
  log.silly('resolveWithNewModule', packageId(pkg), 'checking installable status')
  return isInstallable(pkg, iferr(next, function () {
    if (!pkg._from) {
      pkg._from = pkg._requested.name + '@' + pkg._requested.spec
    }
    addShrinkwrap(pkg, iferr(next, function () {
      addBundled(pkg, iferr(next, function () {
        var parent = earliestInstallable(tree, tree, pkg) || tree
        var child = createChild({
          package: pkg,
          parent: parent,
          path: path.join(parent.path, 'node_modules', pkg.name),
          realpath: path.resolve(parent.realpath, 'node_modules', pkg.name),
          children: pkg._bundled || [],
          isLink: tree.isLink,
          knownInstallable: true
        })
        delete pkg._bundled
        var hasBundled = child.children.length
 
        var replaced = replaceModuleByName(parent, 'children', child)
        if (replaced) removeObsoleteDep(replaced)
        addRequiredDep(tree, child, function () {
          child.location = flatNameFromTree(child)
 
          if (tree.parent && parent !== tree) updatePhantomChildren(tree.parent, child)
 
          if (hasBundled) {
            inflateBundled(child, child, child.children)
          }
 
          if (pkg._shrinkwrap && pkg._shrinkwrap.dependencies) {
            return inflateShrinkwrap(child, pkg._shrinkwrap.dependencies, function (er) {
              next(er, child, log)
            })
          }
 
          next(null, child, log)
        })
      }))
    }))
  }))
}
 
var validatePeerDeps = exports.validatePeerDeps = function (tree, onInvalid) {
  if (!tree.package.peerDependencies) return
  Object.keys(tree.package.peerDependencies).forEach(function (pkgname) {
    var version = tree.package.peerDependencies[pkgname]
    var match = findRequirement(tree.parent || tree, pkgname, npa(pkgname + '@' + version))
    if (!match) onInvalid(tree, pkgname, version)
  })
}
 
exports.validateAllPeerDeps = function (tree, onInvalid) {
  validateAllPeerDeps(tree, onInvalid, {})
}
 
function validateAllPeerDeps (tree, onInvalid, seen) {
  validate('OFO', arguments)
  if (seen[tree.path]) return
  seen[tree.path] = true
  validatePeerDeps(tree, onInvalid)
  tree.children.forEach(function (child) { validateAllPeerDeps(child, onInvalid, seen) })
}
 
// Determine if a module requirement is already met by the tree at or above
// our current location in the tree.
var findRequirement = exports.findRequirement = function (tree, name, requested, requestor) {
  validate('OSO', [tree, name, requested])
  if (!requestor) requestor = tree
  var nameMatch = function (child) {
    return moduleName(child) === name && child.parent && !child.removed
  }
  var versionMatch = function (child) {
    return doesChildVersionMatch(child, requested, requestor)
  }
  if (nameMatch(tree)) {
    // this *is* the module, but it doesn't match the version, so a
    // new copy will have to be installed
    return versionMatch(tree) ? tree : null
  }
 
  var matches = tree.children.filter(nameMatch)
  if (matches.length) {
    matches = matches.filter(versionMatch)
    // the module exists as a dependent, but the version doesn't match, so
    // a new copy will have to be installed above here
    if (matches.length) return matches[0]
    return null
  }
  if (tree.isTop) return null
  return findRequirement(tree.parent, name, requested, requestor)
}
 
// Find the highest level in the tree that we can install this module in.
// If the module isn't installed above us yet, that'd be the very top.
// If it is, then it's the level below where its installed.
var earliestInstallable = exports.earliestInstallable = function (requiredBy, tree, pkg) {
  validate('OOO', arguments)
 
  function undeletedModuleMatches (child) {
    return !child.removed && moduleName(child) === pkg.name
  }
  if (tree.children.some(undeletedModuleMatches)) return null
 
  // If any of the children of this tree have conflicting
  // binaries then we need to decline to install this package here.
  var binaryMatches = pkg.bin && tree.children.some(function (child) {
    if (child.removed || !child.package.bin) return false
    return Object.keys(child.package.bin).some(function (bin) {
      return pkg.bin[bin]
    })
  })
 
  if (binaryMatches) return null
 
  // if this tree location requested the same module then we KNOW it
  // isn't compatible because if it were findRequirement would have
  // found that version.
  var deps = tree.package.dependencies || {}
  if (!tree.removed && requiredBy !== tree && deps[pkg.name]) {
    return null
  }
 
  var devDeps = tree.package.devDependencies || {}
  if (tree.isTop && devDeps[pkg.name]) {
    var requested = npa(pkg.name + '@' + devDeps[pkg.name])
    if (!doesChildVersionMatch({package: pkg}, requested, tree)) {
      return null
    }
  }
 
  if (tree.phantomChildren && tree.phantomChildren[pkg.name]) return null
 
  if (tree.isTop) return tree
  if (tree.isGlobal) return tree
 
  if (npm.config.get('global-style') && tree.parent.isTop) return tree
  if (npm.config.get('legacy-bundling')) return tree
 
  return (earliestInstallable(requiredBy, tree.parent, pkg) || tree)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/flatten-tree.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/flatten-tree.js

Statements: 23.53% (8 / 34)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 25.81% (8 / 31)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44  1 1   1 1 1   1                                           1         1                
'use strict'
var validate = require('aproba')
var moduleName = require('../utils/module-name.js')
 
module.exports = flattenTree
module.exports.flatName = flatName
module.exports.flatNameFromTree = flatNameFromTree
 
function flattenTree (tree) {
  validate('O', arguments)
  var seen = {}
  var flat = {}
  var todo = [[tree, '/']]
  while (todo.length) {
    var next = todo.shift()
    var pkg = next[0]
    seen[pkg.path] = true
    var path = next[1]
    flat[path] = pkg
    if (path !== '/') path += '/'
    for (var ii = 0; ii < pkg.children.length; ++ii) {
      var child = pkg.children[ii]
      if (!seen[child.path]) {
        todo.push([child, flatName(path, child)])
      }
    }
  }
  return flat
}
 
function flatName (path, child) {
  validate('SO', arguments)
  return path + (moduleName(child) || 'TOP')
}
 
function flatNameFromTree (tree) {
  validate('O', arguments)
  if (tree.isTop) return '/'
  var path = flatNameFromTree(tree.parent)
  if (path !== '/') path += '/'
  return flatName(path, tree)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/is-extraneous.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/is-extraneous.js

Statements: 24% (6 / 25)      Branches: 0% (0 / 19)      Functions: 0% (0 / 6)      Lines: 26.09% (6 / 23)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39  1   1         1       1       1           1                                
'use strict'
module.exports = isExtraneous
 
function isExtraneous (tree) {
  var result = !isNotExtraneous(tree)
  return result
}
 
function isNotRequired (tree) {
  return tree.requiredBy && tree.requiredBy.length === 0
}
 
function parentHasNoPjson (tree) {
  return tree.parent && tree.parent.isTop && tree.parent.error
}
 
function topHasNoPjson (tree) {
  var top = tree
  while (!top.isTop) top = top.parent
  return top.error
}
 
function isNotExtraneous (tree, isCycle) {
  if (!isCycle) isCycle = {}
  if (tree.isTop || tree.userRequired) {
    return true
  } else if (isNotRequired(tree) && parentHasNoPjson(tree)) {
    return true
  } else if (isCycle[tree.path]) {
    return topHasNoPjson(tree)
  } else {
    isCycle[tree.path] = true
    return tree.requiredBy && tree.requiredBy.some(function (node) {
      return isNotExtraneous(node, Object.create(isCycle))
    })
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/is-registry-specifier.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/is-registry-specifier.js

Statements: 66.67% (2 / 3)      Branches: 0% (0 / 3)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 6 7 8  1   1        
'use strict'
module.exports = isRegistrySpecifier
 
function isRegistrySpecifier (spec) {
  return spec.type === 'range' || spec.type === 'version' || spec.type === 'tag'
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/mutate-into-logical-tree.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/mutate-into-logical-tree.js

Statements: 12.2% (10 / 82)      Branches: 0% (0 / 40)      Functions: 0% (0 / 16)      Lines: 13.51% (10 / 74)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136  16 16 16 16 16 16               1                                                                                                               1       1                     1                                                                                                    
'use strict'
var union = require('lodash.union')
var without = require('lodash.without')
var validate = require('aproba')
var flattenTree = require('./flatten-tree.js')
var isExtraneous = require('./is-extraneous.js')
var validateAllPeerDeps = require('./deps.js').validateAllPeerDeps
var packageId = require('../utils/package-id.js')
var moduleName = require('../utils/module-name.js')
 
// Return true if tree is a part of a cycle that:
//   A) Never connects to the top of the tree
//   B) Has not not had a point in the cycle arbitraryly declared its top
//      yet.
function isDisconnectedCycle (tree, seen) {
  if (!seen) seen = {}
  if (tree.isTop || tree.cycleTop || tree.requiredBy.length === 0) {
    return false
  } else if (seen[tree.path]) {
    return true
  } else {
    seen[tree.path] = true
    return tree.requiredBy.every(function (node) {
      return isDisconnectedCycle(node, Object.create(seen))
    })
  }
}
 
var mutateIntoLogicalTree = module.exports = function (tree) {
  validate('O', arguments)
 
  validateAllPeerDeps(tree, function (tree, pkgname, version) {
    if (!tree.missingPeers) tree.missingPeers = {}
    tree.missingPeers[pkgname] = version
  })
 
  var flat = flattenTree(tree)
 
  Object.keys(flat).sort().forEach(function (flatname) {
    var node = flat[flatname]
    if (!(node.requiredBy && node.requiredBy.length)) return
 
    if (node.parent) {
      // If a node is a cycle that never reaches the root of the logical
      // tree then we'll leave it attached to the root, or else it
      // would go missing. Further we'll note that this is the node in the
      // cycle that we picked arbitrarily to be the one attached to the root.
      // others will fall
      if (isDisconnectedCycle(node)) {
        node.cycleTop = true
      // Nor do we want to disconnect non-cyclical extraneous modules from the tree.
      } else if (node.requiredBy.length) {
        // regular deps though, we do, as we're moving them into the capable
        // hands of the modules that require them.
        node.parent.children = without(node.parent.children, node)
      }
    }
 
    node.requiredBy.forEach(function (parentNode) {
      parentNode.children = union(parentNode.children, [node])
    })
  })
  return tree
}
 
module.exports.asReadInstalled = function (tree) {
  mutateIntoLogicalTree(tree)
  return translateTree(tree)
}
 
function translateTree (tree) {
  return translateTree_(tree, {})
}
 
function translateTree_ (tree, seen) {
  var pkg = tree.package
  if (seen[tree.path]) return pkg
  seen[tree.path] = pkg
  if (pkg._dependencies) return pkg
  pkg._dependencies = pkg.dependencies
  pkg.dependencies = {}
  tree.children.forEach(function (child) {
    pkg.dependencies[moduleName(child)] = translateTree_(child, seen)
  })
 
  function markMissing (name, requiredBy) {
    if (pkg.dependencies[name]) {
      if (pkg.dependencies[name].missing) return
      pkg.dependencies[name].invalid = true
      pkg.dependencies[name].realName = name
      pkg.dependencies[name].extraneous = false
    } else {
      pkg.dependencies[name] = {
        requiredBy: requiredBy,
        missing: true,
        optional: !!pkg.optionalDependencies[name]
      }
    }
  }
 
  Object.keys(tree.missingDeps).forEach(function (name) {
    markMissing(name, tree.missingDeps[name])
  })
  Object.keys(tree.missingDevDeps).forEach(function (name) {
    markMissing(name, tree.missingDevDeps[name])
  })
  var checkForMissingPeers = (tree.parent ? [] : [tree]).concat(tree.children)
  checkForMissingPeers.filter(function (child) {
    return child.missingPeers
  }).forEach(function (child) {
    Object.keys(child.missingPeers).forEach(function (pkgname) {
      var version = child.missingPeers[pkgname]
      var peerPkg = pkg.dependencies[pkgname]
      if (!peerPkg) {
        peerPkg = pkg.dependencies[pkgname] = {
          _id: pkgname + '@' + version,
          name: pkgname,
          version: version
        }
      }
      if (!peerPkg.peerMissing) peerPkg.peerMissing = []
      peerPkg.peerMissing.push({
        requiredBy: packageId(child),
        requires: pkgname + '@' + version
      })
    })
  })
  pkg.path = tree.path
 
  pkg.error = tree.error
  pkg.extraneous = isExtraneous(tree)
  if (tree.target && tree.parent && !tree.parent.target) pkg.link = tree.realpath
  return pkg
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/realize-shrinkwrap-specifier.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/install/realize-shrinkwrap-specifier.js

Statements: 33.33% (5 / 15)      Branches: 0% (0 / 8)      Functions: 0% (0 / 4)      Lines: 33.33% (5 / 15)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/install/ » realize-shrinkwrap-specifier.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1 1   1 1                               1          
'use strict'
var realizePackageSpecifier = require('realize-package-specifier')
var isRegistrySpecifier = require('./is-registry-specifier.js')
 
module.exports = function (name, sw, where, cb) {
  function lookup (ver, cb) {
    realizePackageSpecifier(name + '@' + ver, where, cb)
  }
  if (sw.resolved) {
    return lookup(sw.resolved, cb)
  } else if (sw.from) {
    return lookup(sw.from, function (err, spec) {
      if (err || isRegistrySpecifier(spec)) {
        return thenUseVersion()
      } else {
        return cb(null, spec)
      }
    })
  } else {
    return thenUseVersion()
  }
  function thenUseVersion () {
    lookup(sw.version, cb)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/

Statements: 22.47% (71 / 316)      Branches: 0% (0 / 152)      Functions: 0% (0 / 73)      Lines: 23.67% (71 / 300)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/search/
File Statements Branches Functions Lines
all-package-metadata.js 19.53% (33 / 169) 0% (0 / 72) 0% (0 / 35) 20.89% (33 / 158)
all-package-search.js 33.33% (7 / 21) 0% (0 / 16) 0% (0 / 6) 33.33% (7 / 21)
esearch.js 32.26% (10 / 31) 0% (0 / 8) 0% (0 / 8) 35.71% (10 / 28)
format-package-stream.js 22.22% (16 / 72) 0% (0 / 33) 0% (0 / 17) 22.22% (16 / 72)
package-filter.js 21.74% (5 / 23) 0% (0 / 23) 0% (0 / 7) 23.81% (5 / 21)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/all-package-metadata.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/all-package-metadata.js

Statements: 19.53% (33 / 169)      Branches: 0% (0 / 72)      Functions: 0% (0 / 35)      Lines: 20.89% (33 / 158)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315    1 1 1 1 1 1 1 1 1 1 1 1 1 1 1                       1 1                                                           1 1                                                                     1 1           1 1                                     1 1                                                                                                           1     1                                                                   1 1                                       1                       1                                 1                                                               1                                    
'use strict'
 
var fs = require('graceful-fs')
var path = require('path')
var mkdir = require('mkdirp')
var chownr = require('chownr')
var npm = require('../npm.js')
var log = require('npmlog')
var cacheFile = require('npm-cache-filename')
var getCacheStat = require('../cache/get-stat.js')
var mapToRegistry = require('../utils/map-to-registry.js')
var jsonstream = require('JSONStream')
var writeStreamAtomic = require('fs-write-stream-atomic')
var ms = require('mississippi')
var sortedUnionStream = require('sorted-union-stream')
var once = require('once')
var gunzip = require('../utils/gunzip-maybe')
 
// Returns a sorted stream of all package metadata. Internally, takes care of
// maintaining its metadata cache and making partial or full remote requests,
// according to staleness, validity, etc.
//
// The local cache must hold certain invariants:
// 1. It must be a proper JSON object
// 2. It must have its keys lexically sorted
// 3. The first entry must be `_updated` with a millisecond timestamp as a val.
// 4. It must include all entries that exist in the metadata endpoint as of
//    the value in `_updated`
module.exports = allPackageMetadata
function allPackageMetadata (staleness) {
  var stream = ms.through.obj()
 
  mapToRegistry('-/all', npm.config, function (er, uri, auth) {
    if (er) return stream.emit('error', er)
 
    var cacheBase = cacheFile(npm.config.get('cache'))(uri)
    var cachePath = path.join(cacheBase, '.cache.json')
 
    createEntryStream(cachePath, uri, auth, staleness, function (err, entryStream, latest, newEntries) {
      if (err) return stream.emit('error', err)
      log.silly('all-package-metadata', 'entry stream created')
      if (entryStream && newEntries) {
        createCacheWriteStream(cachePath, latest, function (err, writeStream) {
          if (err) return stream.emit('error', err)
          log.silly('all-package-metadata', 'output stream created')
          ms.pipeline.obj(entryStream, writeStream, stream)
        })
      } else if (entryStream) {
        ms.pipeline.obj(entryStream, stream)
      } else {
        stream.emit('error', new Error('No search sources available'))
      }
    })
  })
  return stream
}
 
// Creates a stream of the latest available package metadata.
// Metadata will come from a combination of the local cache and remote data.
module.exports._createEntryStream = createEntryStream
function createEntryStream (cachePath, uri, auth, staleness, cb) {
  createCacheEntryStream(cachePath, function (err, cacheStream, cacheLatest) {
    cacheLatest = cacheLatest || 0
    if (err) {
      log.warn('', 'Failed to read search cache. Rebuilding')
      log.silly('all-package-metadata', 'cache read error: ', err)
    }
    createEntryUpdateStream(uri, auth, staleness, cacheLatest, function (err, updateStream, updatedLatest) {
      updatedLatest = updatedLatest || 0
      var latest = updatedLatest || cacheLatest
      if (!cacheStream && !updateStream) {
        return cb(new Error('No search sources available'))
      }
      if (err) {
        log.warn('', 'Search data request failed, search might be stale')
        log.silly('all-package-metadata', 'update request error: ', err)
      }
      if (cacheStream && updateStream) {
        // Deduped, unioned, sorted stream from the combination of both.
        cb(null,
          createMergedStream(cacheStream, updateStream),
          latest,
          !!updatedLatest)
      } else {
        // Either one works if one or the other failed
        cb(null, cacheStream || updateStream, latest, !!updatedLatest)
      }
    })
  })
}
 
// Merges `a` and `b` into one stream, dropping duplicates in favor of entries
// in `b`. Both input streams should already be individually sorted, and the
// returned output stream will have semantics resembling the merge step of a
// plain old merge sort.
module.exports._createMergedStream = createMergedStream
function createMergedStream (a, b) {
  linkStreams(a, b)
  return sortedUnionStream(b, a, function (pkg) { return pkg.name })
}
 
// Reads the local index and returns a stream that spits out package data.
module.exports._createCacheEntryStream = createCacheEntryStream
function createCacheEntryStream (cacheFile, cb) {
  log.verbose('all-package-metadata', 'creating entry stream from local cache')
  log.verbose('all-package-metadata', cacheFile)
  fs.stat(cacheFile, function (err, stat) {
    if (err) return cb(err)
    // TODO - This isn't very helpful if `cacheFile` is empty or just `{}`
    var entryStream = ms.pipeline.obj(
      fs.createReadStream(cacheFile),
      jsonstream.parse('*'),
      // I believe this passthrough is necessary cause `jsonstream` returns
      // weird custom streams that behave funny sometimes.
      ms.through.obj()
    )
    extractUpdated(entryStream, 'cached-entry-stream', cb)
  })
}
 
// Stream of entry updates from the server. If `latest` is `0`, streams the
// entire metadata object from the registry.
module.exports._createEntryUpdateStream = createEntryUpdateStream
function createEntryUpdateStream (all, auth, staleness, latest, cb) {
  log.verbose('all-package-metadata', 'creating remote entry stream')
  var params = {
    timeout: 600,
    follow: true,
    staleOk: true,
    auth: auth,
    streaming: true
  }
  var partialUpdate = false
  if (latest && (Date.now() - latest < (staleness * 1000))) {
    // Skip the request altogether if our `latest` isn't stale.
    log.verbose('all-package-metadata', 'Local data up to date, skipping update')
    return cb(null)
  } else if (latest === 0) {
    log.warn('', 'Building the local index for the first time, please be patient')
    log.verbose('all-package-metadata', 'No cached data: requesting full metadata db')
  } else {
    log.verbose('all-package-metadata', 'Cached data present with timestamp:', latest, 'requesting partial index update')
    all += '/since?stale=update_after&startkey=' + latest
    partialUpdate = true
  }
  npm.registry.request(all, params, function (er, res) {
    if (er) return cb(er)
    log.silly('all-package-metadata', 'request stream opened, code:', res.statusCode)
    // NOTE - The stream returned by `request` seems to be very persnickety
    //        and this is almost a magic incantation to get it to work.
    //        Modify how `res` is used here at your own risk.
    var entryStream = ms.pipeline.obj(
      res,
      ms.through(function (chunk, enc, cb) {
        cb(null, chunk)
      }),
      gunzip(),
      jsonstream.parse('*', function (pkg, key) {
        if (key[0] === '_updated' || key[0][0] !== '_') {
          return pkg
        }
      })
    )
    if (partialUpdate) {
      // The `/all/since` endpoint doesn't return `_updated`, so we
      // just use the request's own timestamp.
      cb(null, entryStream, Date.parse(res.headers.date))
    } else {
      extractUpdated(entryStream, 'entry-update-stream', cb)
    }
  })
}
 
// Both the (full) remote requests and the local index have `_updated` as their
// first returned entries. This is the "latest" unix timestamp for the metadata
// in question. This code does a bit of juggling with the data streams
// so that we can pretend that field doesn't exist, but still extract `latest`
function extractUpdated (entryStream, label, cb) {
  cb = once(cb)
  log.silly('all-package-metadata', 'extracting latest')
  function nope (msg) {
    return function () {
      log.warn('all-package-metadata', label, msg)
      entryStream.removeAllListeners()
      entryStream.destroy()
      cb(new Error(msg))
    }
  }
  var onErr = nope('Failed to read stream')
  var onEnd = nope('Empty or invalid stream')
  entryStream.on('error', onErr)
  entryStream.on('end', onEnd)
  entryStream.once('data', function (latest) {
    log.silly('all-package-metadata', 'got first stream entry for', label, latest)
    entryStream.removeListener('error', onErr)
    entryStream.removeListener('end', onEnd)
    // Because `.once()` unpauses the stream, we re-pause it after the first
    // entry so we don't vomit entries into the void.
    entryStream.pause()
    if (typeof latest === 'number') {
      // The extra pipeline is to return a stream that will implicitly unpause
      // after having an `.on('data')` listener attached, since using this
      // `data` event broke its initial state.
      cb(null, ms.pipeline.obj(entryStream, ms.through.obj()), latest)
    } else {
      cb(new Error('expected first entry to be _updated'))
    }
  })
}
 
// Creates a stream that writes input metadata to the current cache.
// Cache updates are atomic, and the stream closes when *everything* is done.
// The stream is also passthrough, so entries going through it will also
// be output from it.
module.exports._createCacheWriteStream = createCacheWriteStream
function createCacheWriteStream (cacheFile, latest, cb) {
  _ensureCacheDirExists(cacheFile, function (err) {
    if (err) return cb(err)
    log.silly('all-package-metadata', 'creating output stream')
    var outStream = _createCacheOutStream()
    var cacheFileStream = writeStreamAtomic(cacheFile)
    var inputStream = _createCacheInStream(cacheFileStream, outStream, latest)
 
    // Glue together the various streams so they fail together.
    // `cacheFileStream` errors are already handled by the `inputStream`
    // pipeline
    var errEmitted = false
    linkStreams(inputStream, outStream, function () { errEmitted = true })
 
    cacheFileStream.on('close', function () { !errEmitted && outStream.end() })
 
    cb(null, ms.duplex.obj(inputStream, outStream))
  })
}
 
function _ensureCacheDirExists (cacheFile, cb) {
  var cacheBase = path.dirname(cacheFile)
  log.silly('all-package-metadata', 'making sure cache dir exists at', cacheBase)
  getCacheStat(function (er, st) {
    if (er) return cb(er)
    mkdir(cacheBase, function (er, made) {
      if (er) return cb(er)
      chownr(made || cacheBase, st.uid, st.gid, cb)
    })
  })
}
 
function _createCacheOutStream () {
  return ms.pipeline.obj(
    // These two passthrough `through` streams compensate for some
    // odd behavior with `jsonstream`.
    ms.through(),
    jsonstream.parse('*', function (obj, key) {
      // This stream happens to get _updated passed through it, for
      // implementation reasons. We make sure to filter it out cause
      // the fact that it comes t
      if (typeof obj === 'object') {
        return obj
      }
    }),
    ms.through.obj()
  )
}
 
function _createCacheInStream (writer, outStream, latest) {
  var updatedWritten = false
  var inStream = ms.pipeline.obj(
    ms.through.obj(function (pkg, enc, cb) {
      if (!updatedWritten && typeof pkg === 'number') {
        // This is the `_updated` value getting sent through.
        updatedWritten = true
        return cb(null, ['_updated', pkg])
      } else if (typeof pkg !== 'object') {
        this.emit('error', new Error('invalid value written to input stream'))
      } else {
        // The [key, val] format is expected by `jsonstream` for object writing
        cb(null, [pkg.name, pkg])
      }
    }),
    jsonstream.stringifyObject('{', ',', '}'),
    ms.through(function (chunk, enc, cb) {
      // This tees off the buffer data to `outStream`, and then continues
      // the pipeline as usual
      outStream.write(chunk, enc, function () {
        cb(null, chunk)
      })
    }),
    // And finally, we write to the cache file.
    writer
  )
  inStream.write(latest)
  return inStream
}
 
// Links errors between `a` and `b`, preventing cycles, and calls `cb` if
// an error happens, once per error.
function linkStreams (a, b, cb) {
  var lastError = null
  a.on('error', function (err) {
    if (err !== lastError) {
      lastError = err
      b.emit('error', err)
      cb(err)
    }
  })
  b.on('error', function (err) {
    if (err !== lastError) {
      lastError = err
      a.emit('error', err)
      cb(err)
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/all-package-search.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/all-package-search.js

Statements: 33.33% (7 / 21)      Branches: 0% (0 / 16)      Functions: 0% (0 / 6)      Lines: 33.33% (7 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521 1 1   1 1                                       1                 1                                  
var ms = require('mississippi')
var allPackageMetadata = require('./all-package-metadata')
var packageFilter = require('./package-filter.js')
 
module.exports = allPackageSearch
function allPackageSearch (opts) {
  var searchSection = (opts.unicode ? '🤔 ' : '') + 'search'
 
  // Get a stream with *all* the packages. This takes care of dealing
  // with the local cache as well, but that's an internal detail.
  var allEntriesStream = allPackageMetadata(opts.staleness)
 
  // Grab a stream that filters those packages according to given params.
  var filterStream = streamFilter(function (pkg) {
    opts.log.gauge.pulse('search')
    opts.log.gauge.show({section: searchSection, logline: 'scanning ' + pkg.name})
    // Simply 'true' if the package matches search parameters.
    var match = packageFilter(pkg, opts.include, opts.exclude, {
      description: opts.description
    })
    return match
  })
  return ms.pipeline.obj(allEntriesStream, filterStream)
}
 
function streamFilter (filter) {
  return ms.through.obj(function (data, enc, cb) {
    if (filter(data)) {
      this.push(standardizePkg(data))
    }
    cb()
  })
}
 
function standardizePkg (data) {
  return {
    name: data.name,
    description: data.description,
    maintainers: (data.maintainers || []).map(function (m) {
      return { username: m.name, email: m.email }
    }),
    keywords: data.keywords || [],
    version: Object.keys(data.versions || {})[0] || [],
    date: (
      data.time &&
      data.time.modified &&
      new Date(data.time.modified)
    ) || null
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/esearch.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/esearch.js

Statements: 32.26% (10 / 31)      Branches: 0% (0 / 8)      Functions: 0% (0 / 8)      Lines: 35.71% (10 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66    1 1 1 1 1 1   1   1                         1                                                                         1        
'use strict'
 
var npm = require('../npm.js')
var log = require('npmlog')
var mapToRegistry = require('../utils/map-to-registry.js')
var jsonstream = require('JSONStream')
var ms = require('mississippi')
var gunzip = require('../utils/gunzip-maybe')
 
module.exports = esearch
 
function esearch (opts) {
  var stream = ms.through.obj()
 
  mapToRegistry('-/v1/search', npm.config, function (er, uri, auth) {
    if (er) return stream.emit('error', er)
    createResultStream(uri, auth, opts, function (err, resultStream) {
      if (err) return stream.emit('error', err)
      ms.pipeline.obj(resultStream, stream)
    })
  })
  return stream
}
 
function createResultStream (uri, auth, opts, cb) {
  log.verbose('esearch', 'creating remote entry stream')
  var params = {
    timeout: 600,
    follow: true,
    staleOk: true,
    auth: auth,
    streaming: true
  }
  var q = buildQuery(opts)
  npm.registry.request(uri + '?text=' + encodeURIComponent(q) + '&size=' + opts.limit, params, function (err, res) {
    if (err) return cb(err)
    log.silly('esearch', 'request stream opened, code:', res.statusCode)
    // NOTE - The stream returned by `request` seems to be very persnickety
    //        and this is almost a magic incantation to get it to work.
    //        Modify how `res` is used here at your own risk.
    var entryStream = ms.pipeline.obj(
      res,
      ms.through(function (chunk, enc, cb) {
        cb(null, chunk)
      }),
      gunzip(),
      jsonstream.parse('objects.*.package', function (data) {
        return {
          name: data.name,
          description: data.description,
          maintainers: data.maintainers,
          keywords: data.keywords,
          version: data.version,
          date: data.date ? new Date(data.date) : null
        }
      })
    )
    return cb(null, entryStream)
  })
}
 
function buildQuery (opts) {
  return opts.include.join(' ')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/format-package-stream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/format-package-stream.js

Statements: 22.22% (16 / 72)      Branches: 0% (0 / 33)      Functions: 0% (0 / 17)      Lines: 22.22% (16 / 72)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174    1 1 1                               1 1                 1               1             1                                                                               1 1   1                                                   1                   1                     1             1               1                                              
'use strict'
 
var ms = require('mississippi')
var jsonstream = require('JSONStream')
var columnify = require('columnify')
 
// This module consumes package data in the following format:
//
// {
//   name: String,
//   description: String,
//   maintainers: [{ username: String, email: String }],
//   keywords: String | [String],
//   version: String,
//   date: Date // can be null,
// }
//
// The returned stream will format this package data
// into a byte stream of formatted, displayable output.
 
module.exports = formatPackageStream
function formatPackageStream (opts) {
  opts = opts || {}
  if (opts.json) {
    return jsonOutputStream()
  } else {
    return textOutputStream(opts)
  }
}
 
function jsonOutputStream () {
  return ms.pipeline.obj(
    ms.through.obj(),
    jsonstream.stringify('[', ',', ']'),
    ms.through()
  )
}
 
function textOutputStream (opts) {
  var line = 0
  return ms.through.obj(function (pkg, enc, cb) {
    cb(null, prettify(pkg, ++line, opts))
  })
}
 
function prettify (data, num, opts) {
  opts = opts || {}
  var truncate = !opts.long
 
  var pkg = normalizePackage(data, opts)
 
  var columns = opts.description
  ? ['name', 'description', 'author', 'date', 'version', 'keywords']
  : ['name', 'author', 'date', 'version', 'keywords']
 
  if (opts.parseable) {
    return columns.map(function (col) {
      return pkg[col] && ('' + pkg[col]).replace(/\t/g, ' ')
    }).join('\t')
  }
 
  var output = columnify(
    [pkg],
    {
      include: columns,
      showHeaders: num <= 1,
      columnSplitter: ' | ',
      truncate: truncate,
      config: {
        name: { minWidth: 25, maxWidth: 25, truncate: false, truncateMarker: '' },
        description: { minWidth: 20, maxWidth: 20 },
        author: { minWidth: 15, maxWidth: 15 },
        date: { maxWidth: 11 },
        version: { minWidth: 8, maxWidth: 8 },
        keywords: { maxWidth: Infinity }
      }
    }
  )
  output = trimToMaxWidth(output)
  if (opts.color) {
    output = highlightSearchTerms(output, opts.args)
  }
  return output
}
 
var colors = [31, 33, 32, 36, 34, 35]
var cl = colors.length
 
function addColorMarker (str, arg, i) {
  var m = i % cl + 1
  var markStart = String.fromCharCode(m)
  var markEnd = String.fromCharCode(0)
 
  if (arg.charAt(0) === '/') {
    return str.replace(
      new RegExp(arg.substr(1, arg.length - 2), 'gi'),
      function (bit) { return markStart + bit + markEnd }
    )
  }
 
  // just a normal string, do the split/map thing
  var pieces = str.toLowerCase().split(arg.toLowerCase())
  var p = 0
 
  return pieces.map(function (piece) {
    piece = str.substr(p, piece.length)
    var mark = markStart +
               str.substr(p + piece.length, arg.length) +
               markEnd
    p += piece.length + arg.length
    return piece + mark
  }).join('')
}
 
function colorize (line) {
  for (var i = 0; i < cl; i++) {
    var m = i + 1
    var color = '\u001B[' + colors[i] + 'm'
    line = line.split(String.fromCharCode(m)).join(color)
  }
  var uncolor = '\u001B[0m'
  return line.split('\u0000').join(uncolor)
}
 
function getMaxWidth () {
  var cols
  try {
    var tty = require('tty')
    var stdout = process.stdout
    cols = !tty.isatty(stdout.fd) ? Infinity : process.stdout.getWindowSize()[0]
    cols = (cols === 0) ? Infinity : cols
  } catch (ex) { cols = Infinity }
  return cols
}
 
function trimToMaxWidth (str) {
  var maxWidth = getMaxWidth()
  return str.split('\n').map(function (line) {
    return line.slice(0, maxWidth)
  }).join('\n')
}
 
function highlightSearchTerms (str, terms) {
  terms.forEach(function (arg, i) {
    str = addColorMarker(str, arg, i)
  })
 
  return colorize(str).trim()
}
 
function normalizePackage (data, opts) {
  opts = opts || {}
  return {
    name: data.name,
    description: opts.description ? data.description : '',
    author: (data.maintainers || []).map(function (m) {
      return '=' + m.username
    }).join(' '),
    keywords: Array.isArray(data.keywords)
    ? data.keywords.join(' ')
    : typeof data.keywords === 'string'
    ? data.keywords.replace(/[,\s]+/, ' ')
    : '',
    version: data.version,
    date: data.date &&
          (data.date.toISOString() // remove time
            .split('T').join(' ')
            .replace(/:[0-9]{2}\.[0-9]{3}Z$/, ''))
            .slice(0, -5) ||
          'prehistoric'
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/package-filter.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/search/package-filter.js

Statements: 21.74% (5 / 23)      Branches: 0% (0 / 23)      Functions: 0% (0 / 7)      Lines: 23.81% (5 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43    1 1         1                           1                     1                  
'use strict'
 
module.exports = filter
function filter (data, include, exclude, opts) {
  return typeof data === 'object' &&
         filterWords(data, include, exclude, opts)
}
 
function getWords (data, opts) {
  return [ data.name ]
  .concat((opts && opts.description) ? data.description : [])
  .concat((data.maintainers || []).map(function (m) {
    return '=' + m.name
  }))
  .concat(data.versions && data.versions.length && data.url && ('<' + data.url + '>'))
  .concat(data.keywords || [])
  .map(function (f) { return f && f.trim && f.trim() })
  .filter(function (f) { return f })
  .join(' ')
  .toLowerCase()
}
 
function filterWords (data, include, exclude, opts) {
  var words = getWords(data, opts)
  for (var i = 0, l = include.length; i < l; i++) {
    if (!match(words, include[i])) return false
  }
  for (i = 0, l = exclude.length; i < l; i++) {
    if (match(words, exclude[i])) return false
  }
  return true
}
 
function match (words, pattern) {
  if (pattern.charAt(0) === '/') {
    pattern = pattern.replace(/\/$/, '')
    pattern = new RegExp(pattern.substr(1, pattern.length - 1))
    return words.match(pattern)
  }
  return words.indexOf(pattern) !== -1
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/

Statements: 23.85% (307 / 1287)      Branches: 3.42% (24 / 702)      Functions: 4.57% (8 / 175)      Lines: 25.87% (304 / 1175)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/utils/
File Statements Branches Functions Lines
ansi-trim.js 50% (2 / 4) 100% (0 / 0) 0% (0 / 1) 50% (2 / 4)
correct-mkdir.js 17.57% (13 / 74) 0% (0 / 42) 0% (0 / 9) 19.12% (13 / 68)
depr-check.js 33.33% (4 / 12) 0% (0 / 6) 0% (0 / 1) 40% (4 / 10)
escape-arg.js 44.44% (4 / 9) 0% (0 / 4) 0% (0 / 1) 44.44% (4 / 9)
escape-exec-path.js 38.46% (5 / 13) 0% (0 / 6) 0% (0 / 2) 41.67% (5 / 12)
gently-rm.js 22.7% (37 / 163) 0% (0 / 79) 0% (0 / 26) 24.18% (37 / 153)
get-publish-config.js 31.25% (5 / 16) 0% (0 / 2) 0% (0 / 2) 31.25% (5 / 16)
git.js 43.33% (13 / 30) 0% (0 / 8) 0% (0 / 6) 43.33% (13 / 30)
gunzip-maybe.js 40% (6 / 15) 0% (0 / 5) 0% (0 / 3) 40% (6 / 15)
is-windows-bash.js 100% (2 / 2) 50% (1 / 2) 100% (0 / 0) 100% (2 / 2)
is-windows-shell.js 100% (3 / 3) 50% (1 / 2) 100% (0 / 0) 100% (3 / 3)
is-windows.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
lifecycle.js 15.3% (43 / 281) 0.65% (1 / 154) 3.13% (1 / 32) 16.23% (43 / 265)
link.js 24.49% (12 / 49) 0% (0 / 22) 0% (0 / 8) 27.91% (12 / 43)
locker.js 25.58% (11 / 43) 0% (0 / 12) 0% (0 / 6) 26.83% (11 / 41)
map-to-registry.js 10.91% (6 / 55) 0% (0 / 28) 0% (0 / 2) 11.11% (6 / 54)
metrics.js 28.89% (13 / 45) 0% (0 / 18) 0% (0 / 6) 32.5% (13 / 40)
module-name.js 32.26% (10 / 31) 0% (0 / 16) 0% (0 / 3) 40% (10 / 25)
no-progress-while-running.js 33.33% (6 / 18) 0% (0 / 8) 0% (0 / 4) 40% (6 / 15)
output.js 40% (2 / 5) 100% (0 / 0) 0% (0 / 1) 40% (2 / 5)
package-id.js 22.22% (2 / 9) 0% (0 / 8) 0% (0 / 1) 25% (2 / 8)
parse-json.js 63.64% (7 / 11) 50% (1 / 2) 66.67% (2 / 3) 63.64% (7 / 11)
pick-manifest-from-registry-metadata.js 28.57% (4 / 14) 0% (0 / 13) 0% (0 / 1) 28.57% (4 / 14)
pulse-till-done.js 33.33% (5 / 15) 0% (0 / 6) 0% (0 / 3) 35.71% (5 / 14)
read-local-package.js 44.44% (4 / 9) 0% (0 / 4) 0% (0 / 2) 50% (4 / 8)
spawn.js 14.29% (6 / 42) 0% (0 / 20) 0% (0 / 5) 17.65% (6 / 34)
tar.js 15.38% (38 / 247) 2.9% (6 / 207) 0% (0 / 35) 18.1% (38 / 210)
temp-filename.js 75% (3 / 4) 100% (0 / 0) 0% (0 / 1) 75% (3 / 4)
umask.js 50% (5 / 10) 0% (0 / 2) 0% (0 / 2) 50% (5 / 10)
unsupported.js 47.62% (10 / 21) 25% (1 / 4) 66.67% (2 / 3) 47.62% (10 / 21)
usage.js 100% (20 / 20) 92.86% (13 / 14) 100% (2 / 2) 100% (17 / 17)
warn-deprecated.js 31.25% (5 / 16) 0% (0 / 8) 25% (1 / 4) 38.46% (5 / 13)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/ansi-trim.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/ansi-trim.js

Statements: 50% (2 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 50% (2 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 91           1    
function ansiTrim (str) {
  var r = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' +
        '\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g')
  return str.replace(r, '')
}
 
module.exports = ansiTrim
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/correct-mkdir.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/correct-mkdir.js

Statements: 17.57% (13 / 74)      Branches: 0% (0 / 42)      Functions: 0% (0 / 9)      Lines: 19.12% (13 / 68)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 1251 1 1 1 1 1     1 1 1                                                             1                                         1                                                                                       1                     1              
var chownr = require('chownr')
var dezalgo = require('dezalgo')
var fs = require('graceful-fs')
var inflight = require('inflight')
var log = require('npmlog')
var mkdirp = require('mkdirp')
 
// memoize the directories created by this step
var stats = {}
var effectiveOwner
module.exports = function correctMkdir (path, cb) {
  cb = dezalgo(cb)
  cb = inflight('correctMkdir:' + path, cb)
  if (!cb) {
    return log.verbose('correctMkdir', path, 'correctMkdir already in flight; waiting')
  } else {
    log.verbose('correctMkdir', path, 'correctMkdir not in flight; initializing')
  }
 
  if (stats[path]) return cb(null, stats[path])
 
  fs.stat(path, function (er, st) {
    if (er) return makeDirectory(path, cb)
 
    if (!st.isDirectory()) {
      log.error('correctMkdir', 'invalid dir %s', path)
      return cb(er)
    }
 
    var ownerStats = calculateOwner()
    // there's always a chance the permissions could have been frobbed, so fix
    if (st.uid !== ownerStats.uid) {
      stats[path] = ownerStats
      setPermissions(path, ownerStats, cb)
    } else {
      stats[path] = st
      cb(null, stats[path])
    }
  })
}
 
function calculateOwner () {
  if (!effectiveOwner) {
    effectiveOwner = { uid: 0, gid: 0 }
 
    // Pretty much only on windows
    if (!process.getuid) {
      return effectiveOwner
    }
 
    effectiveOwner.uid = +process.getuid()
    effectiveOwner.gid = +process.getgid()
 
    if (effectiveOwner.uid === 0) {
      if (process.env.SUDO_UID) effectiveOwner.uid = +process.env.SUDO_UID
      if (process.env.SUDO_GID) effectiveOwner.gid = +process.env.SUDO_GID
    }
  }
 
  return effectiveOwner
}
 
function makeDirectory (path, cb) {
  cb = inflight('makeDirectory:' + path, cb)
  if (!cb) {
    return log.verbose('makeDirectory', path, 'creation already in flight; waiting')
  } else {
    log.verbose('makeDirectory', path, 'creation not in flight; initializing')
  }
 
  var owner = calculateOwner()
 
  if (!process.getuid) {
    return mkdirp(path, function (er) {
      log.verbose('makeCacheDir', 'UID & GID are irrelevant on', process.platform)
 
      stats[path] = owner
      return cb(er, stats[path])
    })
  }
 
  if (owner.uid !== 0 || !process.env.HOME) {
    log.silly(
      'makeDirectory', path,
      'uid:', owner.uid,
      'gid:', owner.gid
    )
    stats[path] = owner
    mkdirp(path, afterMkdir)
  } else {
    fs.stat(process.env.HOME, function (er, st) {
      if (er) {
        log.error('makeDirectory', 'homeless?')
        return cb(er)
      }
 
      log.silly(
        'makeDirectory', path,
        'uid:', st.uid,
        'gid:', st.gid
      )
      stats[path] = st
      mkdirp(path, afterMkdir)
    })
  }
 
  function afterMkdir (er, made) {
    if (er || !stats[path] || isNaN(stats[path].uid) || isNaN(stats[path].gid)) {
      return cb(er, stats[path])
    }
 
    if (!made) return cb(er, stats[path])
 
    setPermissions(made, stats[path], cb)
  }
}
 
function setPermissions (path, st, cb) {
  chownr(path, st.uid, st.gid, function (er) {
    if (er && er.code === 'ENOENT') return cb(null, st)
    return cb(er, st)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/depr-check.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/depr-check.js

Statements: 33.33% (4 / 12)      Branches: 0% (0 / 6)      Functions: 0% (0 / 1)      Lines: 40% (4 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 151   1 1 1                    
var log = require('npmlog')
 
var deprecated = {}
var deprWarned = {}
module.exports = function deprCheck (data) {
  if (deprecated[data._id]) data.deprecated = deprecated[data._id]
  if (data.deprecated) deprecated[data._id] = data.deprecated
  else return
  if (!deprWarned[data._id]) {
    deprWarned[data._id] = true
    log.warn('deprecated', '%s: %s', data._id, data.deprecated)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/escape-arg.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/escape-arg.js

Statements: 44.44% (4 / 9)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 44.44% (4 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29  1 1                       1   1                        
'use strict'
var path = require('path')
var isWindowsShell = require('./is-windows-shell.js')
 
/*
Escape the name of an executable suitable for passing to the system shell.
 
Windows is easy, wrap in double quotes and you're done, as there's no
facility to create files with quotes in their names.
 
Unix-likes are a little more complicated, wrap in single quotes and escape
any single quotes in the filename.
*/
 
module.exports = escapify
 
function escapify (str) {
  if (isWindowsShell) {
    return '"' + path.normalize(str) + '"'
  } else {
    if (/[^-_.~/\w]/.test(str)) {
      return "'" + str.replace(/'/g, "'\"'\"'") + "'"
    } else {
      return str
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/escape-exec-path.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/escape-exec-path.js

Statements: 38.46% (5 / 13)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 41.67% (5 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32  1 1                       1   1         1                    
'use strict'
var path = require('path')
var isWindowsShell = require('./is-windows-shell.js')
 
/*
Escape the name of an executable suitable for passing to the system shell.
 
Windows is easy, wrap in double quotes and you're done, as there's no
facility to create files with quotes in their names.
 
Unix-likes are a little more complicated, wrap in single quotes and escape
any single quotes in the filename.
*/
 
module.exports = escapify
 
function windowsQuotes (str) {
  if (!/ /.test(str)) return str
  return '"' + str + '"'
}
 
function escapify (str) {
  if (isWindowsShell) {
    return path.normalize(str).split(/\\/).map(windowsQuotes).join('\\')
  } else if (/[^-_.~/\w]/.test(str)) {
    return "'" + str.replace(/'/g, "'\"'\"'") + "'"
  } else {
    return str
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/gently-rm.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/gently-rm.js

Statements: 22.7% (37 / 163)      Branches: 0% (0 / 79)      Functions: 0% (0 / 26)      Lines: 24.18% (37 / 153)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299      1   1 1 1 1 1 1 1 1 1 1 1 1 1 1   1                                                                                                                                                   1                   1 1                                                                                                           1               1       1       1                   1                             1       1     1                                   1   1                                   1       1         1             1 1 1                             1 1                                      
// only remove the thing if it's a symlink into a specific folder. This is
// a very common use-case of npm's, but not so common elsewhere.
 
exports = module.exports = gentlyRm
 
var resolve = require('path').resolve
var dirname = require('path').dirname
var normalize = require('path').normalize
var validate = require('aproba')
var log = require('npmlog')
var lstat = require('graceful-fs').lstat
var readlink = require('graceful-fs').readlink
var isInside = require('path-is-inside')
var vacuum = require('fs-vacuum')
var chain = require('slide').chain
var asyncMap = require('slide').asyncMap
var readCmdShim = require('read-cmd-shim')
var iferr = require('iferr')
var npm = require('../npm.js')
 
function gentlyRm (target, gently, base, cb) {
  if (!cb) {
    cb = base
    base = undefined
  }
 
  if (!cb) {
    cb = gently
    gently = false
  }
 
  log.silly(
    'gentlyRm',
    target,
    'is being', gently ? 'gently removed' : 'purged',
    base ? 'from base ' + base : ''
  )
 
  // never rm the root, prefix, or bin dirs
  //
  // globals included because of `npm link` -- as far as the package
  // requesting the link is concerned, the linked package is always
  // installed globally
  var prefixes = [
    npm.prefix,
    npm.globalPrefix,
    npm.dir,
    npm.root,
    npm.globalDir,
    npm.bin,
    npm.globalBin
  ]
 
  var targetPath = normalize(resolve(npm.prefix, target))
  if (prefixes.indexOf(targetPath) !== -1) {
    log.verbose('gentlyRm', targetPath, "is part of npm and can't be removed")
    return cb(new Error('May not delete: ' + targetPath))
  }
  var options = { log: log.silly.bind(log, 'vacuum-fs') }
  if (npm.config.get('force') || !gently) options.purge = true
  if (base) options.base = normalize(resolve(npm.prefix, base))
 
  if (!gently) {
    log.verbose('gentlyRm', "don't care about contents; nuking", targetPath)
    return vacuum(targetPath, options, cb)
  }
 
  var parent = options.base = options.base || normalize(npm.prefix)
 
  // Do all the async work we'll need to do in order to tell if this is a
  // safe operation
  chain([
    [isEverInside, parent, prefixes],
    [readLinkOrShim, targetPath],
    [isEverInside, targetPath, prefixes],
    [isEverInside, targetPath, [parent]]
  ], function (er, results) {
    if (er) {
      if (er.code === 'ENOENT') return cb()
      return cb(er)
    }
    var parentInfo = {
      path: parent,
      managed: results[0]
    }
    var targetInfo = {
      path: targetPath,
      symlink: results[1],
      managed: results[2],
      inParent: results[3]
    }
 
    isSafeToRm(parentInfo, targetInfo, iferr(cb, thenRemove))
 
    function thenRemove (toRemove, removeBase) {
      if (!toRemove) return cb()
      if (removeBase) options.base = removeBase
      log.verbose('gentlyRm', options.purge ? 'Purging' : 'Vacuuming',
        toRemove, 'up to', options.base)
      return vacuum(toRemove, options, cb)
    }
  })
}
 
exports._isSafeToRm = isSafeToRm
function isSafeToRm (parent, target, cb) {
  log.silly('gentlyRm', 'parent.path =', parent.path)
  log.silly('gentlyRm', 'parent.managed =',
    parent.managed && parent.managed.target + ' is in ' + parent.managed.path)
  log.silly('gentlyRm', 'target.path = ', target.path)
  log.silly('gentlyRm', 'target.symlink =', target.symlink)
  log.silly('gentlyRm', 'target.managed =',
    target.managed && target.managed.target + ' is in ' + target.managed.path)
  log.silly('gentlyRm', 'target.inParent = ', target.inParent)
 
  // The parent directory or something it symlinks to must eventually be in
  // a folder that npm maintains.
  if (!parent.managed) {
    log.verbose('gentlyRm', parent.path,
      'is not contained in any diretory npm is known to control or ' +
      'any place they link to')
    return cb(clobberFail(target.path, 'containing path ' + parent.path +
      " isn't under npm's control"))
  }
 
  // The target or something it symlinks to must eventually be in the parent
  // or something the parent symlinks to
  if (target.inParent) {
    var actualTarget = target.inParent.target
    var targetsParent = target.inParent.path
    // if the target.path was what we found in some version of parent, remove
    // using that parent as the base
    if (target.path === actualTarget) {
      return cb(null, target.path, targetsParent)
    } else {
      // If something the target.path links to was what was found, just
      // remove target.path in the location it was found.
      return cb(null, target.path, dirname(target.path))
    }
  }
 
  // If the target is in a managed directory and is in a symlink, but was
  // not in our parent that usually means someone else installed a bin file
  // with the same name as one of our bin files.
  if (target.managed && target.symlink) {
    log.warn('gentlyRm', 'not removing', target.path,
      "as it wasn't installed by", parent.path)
    return cb()
  }
 
  if (target.symlink) {
    return cb(clobberFail(target.path, target.symlink +
      ' symlink target is not controlled by npm ' + parent.path))
  } else {
    return cb(clobberFail(target.path, 'is outside ' + parent.path +
      ' and not a link'))
  }
}
 
function clobberFail (target, msg) {
  validate('SS', arguments)
  var er = new Error('Refusing to delete ' + target + ': ' + msg)
  er.code = 'EEXIST'
  er.path = target
  return er
}
 
function isENOENT (err) {
  return err && err.code === 'ENOENT'
}
 
function notENOENT (err) {
  return !isENOENT(err)
}
 
function skipENOENT (cb) {
  return function (err, value) {
    if (isENOENT(err)) {
      return cb(null, false)
    } else {
      return cb(err, value)
    }
  }
}
 
function errorsToValues (fn) {
  return function () {
    var args = Array.prototype.slice.call(arguments)
    var cb = args.pop()
    args.push(function (err, value) {
      if (err) {
        return cb(null, err)
      } else {
        return cb(null, value)
      }
    })
    fn.apply(null, args)
  }
}
 
function isNotError (value) {
  return !(value instanceof Error)
}
 
exports._isEverInside = isEverInside
// return the first of path, where target (or anything it symlinks to)
// isInside the path (or anything it symlinks to)
function isEverInside (target, paths, cb) {
  validate('SAF', arguments)
  asyncMap(paths, errorsToValues(readAllLinks), iferr(cb, function (resolvedPaths) {
    var errorFree = resolvedPaths.filter(isNotError)
    if (errorFree.length === 0) {
      var badErrors = resolvedPaths.filter(notENOENT)
      if (badErrors.length === 0) {
        return cb(null, false)
      } else {
        return cb(badErrors[0])
      }
    }
    readAllLinks(target, iferr(skipENOENT(cb), function (targets) {
      cb(null, areAnyInsideAny(targets, errorFree))
    }))
  }))
}
 
exports._areAnyInsideAny = areAnyInsideAny
// Return the first path found that any target is inside
function areAnyInsideAny (targets, paths) {
  validate('AA', arguments)
  var toCheck = []
  paths.forEach(function (path) {
    targets.forEach(function (target) {
      toCheck.push([target, path])
    })
  })
  for (var ii = 0; ii < toCheck.length; ++ii) {
    var target = toCheck[ii][0]
    var path = toCheck[ii][1]
    var inside = isInside(target, path)
    if (!inside) log.silly('isEverInside', target, 'is not inside', path)
    if (inside && path) return inside && path && {target: target, path: path}
  }
  return false
}
 
exports._readAllLinks = readAllLinks
// resolves chains of symlinks of unlimited depth, returning a list of paths
// it's seen in the process when it hits either a symlink cycle or a
// non-symlink
function readAllLinks (path, cb) {
  validate('SF', arguments)
  var seen = {}
  _readAllLinks(path)
 
  function _readAllLinks (path) {
    if (seen[path]) return cb(null, Object.keys(seen))
    seen[path] = true
    resolveSymlink(path, iferr(cb, _readAllLinks))
  }
}
 
exports._resolveSymlink = resolveSymlink
var resolvedPaths = {}
function resolveSymlink (symlink, cb) {
  validate('SF', arguments)
  var cached = resolvedPaths[symlink]
  if (cached) return cb(null, cached)
 
  readLinkOrShim(symlink, iferr(cb, function (symlinkTarget) {
    if (symlinkTarget) {
      resolvedPaths[symlink] = resolve(dirname(symlink), symlinkTarget)
    } else {
      resolvedPaths[symlink] = symlink
    }
    return cb(null, resolvedPaths[symlink])
  }))
}
 
exports._readLinkOrShim = readLinkOrShim
function readLinkOrShim (path, cb) {
  validate('SF', arguments)
  lstat(path, iferr(cb, function (stat) {
    if (stat.isSymbolicLink()) {
      readlink(path, cb)
    } else {
      readCmdShim(path, function (er, source) {
        if (!er) return cb(null, source)
        // lstat wouldn't return an error on these, so we don't either.
        if (er.code === 'ENOTASHIM' || er.code === 'EISDIR') {
          return cb(null, null)
        } else {
          return cb(er)
        }
      })
    }
  }))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/get-publish-config.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/get-publish-config.js

Statements: 31.25% (5 / 16)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 31.25% (5 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 271 1 1   1   1                                        
var Conf = require('../config/core.js').Conf
var CachingRegClient = require('../cache/caching-client.js')
var log = require('npmlog')
 
module.exports = getPublishConfig
 
function getPublishConfig (publishConfig, defaultConfig, defaultClient) {
  var config = defaultConfig
  var client = defaultClient
  log.verbose('getPublishConfig', publishConfig)
  if (publishConfig) {
    config = new Conf(defaultConfig)
    config.save = defaultConfig.save.bind(defaultConfig)
 
    // don't modify the actual publishConfig object, in case we have
    // to set a login token or some other data.
    config.unshift(Object.keys(publishConfig).reduce(function (s, k) {
      s[k] = publishConfig[k]
      return s
    }, {}))
    client = new CachingRegClient(config)
  }
 
  return { config: config, client: client }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/git.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/git.js

Statements: 43.33% (13 / 30)      Branches: 0% (0 / 8)      Functions: 0% (0 / 6)      Lines: 43.33% (13 / 30)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49    30 30 30   30 30 30 30 30         1       1           1         1         1                          
// handle some git configuration for windows
 
exports.spawn = spawnGit
exports.chainableExec = chainableExec
exports.whichAndExec = whichAndExec
 
var exec = require('child_process').execFile
var spawn = require('./spawn')
var npm = require('../npm.js')
var which = require('which')
var git = npm.config.get('git')
var assert = require('assert')
var log = require('npmlog')
var noProgressTillDone = require('./no-progress-while-running.js').tillDone
 
function prefixGitArgs () {
  return process.platform === 'win32' ? ['-c', 'core.longpaths=true'] : []
}
 
function execGit (args, options, cb) {
  log.info('git', args)
  var fullArgs = prefixGitArgs().concat(args || [])
  return exec(git, fullArgs, options, noProgressTillDone(cb))
}
 
function spawnGit (args, options) {
  log.info('git', args)
  return spawn(git, prefixGitArgs().concat(args || []), options)
}
 
function chainableExec () {
  var args = Array.prototype.slice.call(arguments)
  return [execGit].concat(args)
}
 
function whichAndExec (args, options, cb) {
  assert.equal(typeof cb, 'function', 'no callback provided')
  // check for git
  which(git, function (err) {
    if (err) {
      err.code = 'ENOGIT'
      return cb(err)
    }
 
    execGit(args, options, cb)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/gunzip-maybe.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/gunzip-maybe.js

Statements: 40% (6 / 15)      Branches: 0% (0 / 5)      Functions: 0% (0 / 3)      Lines: 40% (6 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 241 1 1   1       1 1                            
var duplex = require('mississippi').duplex
var through = require('mississippi').through
var zlib = require('zlib')
 
function hasGzipHeader (c) {
  return c[0] === 0x1F && c[1] === 0x8B && c[2] === 0x08
}
 
module.exports = gunzip
function gunzip () {
  var stream = duplex()
  var peeker = through(function (chunk, enc, cb) {
    var newStream = hasGzipHeader(chunk)
    ? zlib.createGunzip()
    : through()
    stream.setReadable(newStream)
    stream.setWritable(newStream)
    stream.write(chunk)
  })
  stream.setWritable(peeker)
  return stream
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/is-windows-bash.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/is-windows-bash.js

Statements: 100% (2 / 2)      Branches: 50% (1 / 2)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5  1 1    
'use strict'
var isWindows = require('./is-windows.js')
module.exports = isWindows && /^MINGW(32|64)$/.test(process.env.MSYSTEM)
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/is-windows-shell.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/is-windows-shell.js

Statements: 100% (3 / 3)      Branches: 50% (1 / 2)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 5 6  1 1 1    
'use strict'
var isWindows = require('./is-windows.js')
var isWindowsBash = require('./is-windows-bash.js')
module.exports = isWindows && !isWindowsBash
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/is-windows.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/is-windows.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4  1    
'use strict'
module.exports = process.platform === 'win32'
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/lifecycle.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/lifecycle.js

Statements: 15.3% (43 / 281)      Branches: 0.65% (1 / 154)      Functions: 3.13% (1 / 32)      Lines: 16.23% (43 / 265)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 4501 1 1 1   1 1 1 1 1 1 1 1 1 1 1 1 1     1                 1       1                                                                                                       1       1                                                               1                                           1                                                                   1                         1                   1 1 1               1                                                         1 1                                                                                           1                                             1     1                 1                           1                                                                                                                                                                                                       1 1     3 3 3         3      
exports = module.exports = lifecycle
exports.cmd = cmd
exports.makeEnv = makeEnv
exports._incorrectWorkingDirectory = _incorrectWorkingDirectory
 
var log = require('npmlog')
var spawn = require('./spawn')
var npm = require('../npm.js')
var path = require('path')
var fs = require('graceful-fs')
var chain = require('slide').chain
var Stream = require('stream').Stream
var PATH = 'PATH'
var uidNumber = require('uid-number')
var umask = require('./umask')
var usage = require('./usage')
var output = require('./output.js')
var which = require('which')
 
// windows calls it's path 'Path' usually, but this is not guaranteed.
Iif (process.platform === 'win32') {
  PATH = 'Path'
  Object.keys(process.env).forEach(function (e) {
    if (e.match(/^PATH$/i)) {
      PATH = e
    }
  })
}
 
function logid (pkg, stage) {
  return pkg._id + '~' + stage + ':'
}
 
function lifecycle (pkg, stage, wd, unsafe, failOk, cb) {
  if (typeof cb !== 'function') {
    cb = failOk
    failOk = false
  }
  if (typeof cb !== 'function') {
    cb = unsafe
    unsafe = false
  }
  if (typeof cb !== 'function') {
    cb = wd
    wd = null
  }
 
  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error('Invalid package data'))
 
  log.info('lifecycle', logid(pkg, stage), pkg._id)
  if (!pkg.scripts) pkg.scripts = {}
 
  if (npm.config.get('ignore-scripts')) {
    log.info('lifecycle', logid(pkg, stage), 'ignored because ignore-scripts is set to true', pkg._id)
    pkg.scripts = {}
  }
 
  validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
    if (er) return cb(er)
 
    unsafe = unsafe || npm.config.get('unsafe-perm')
 
    if ((wd.indexOf(npm.dir) !== 0 || _incorrectWorkingDirectory(wd, pkg)) &&
        !unsafe && pkg.scripts[stage]) {
      log.warn('lifecycle', logid(pkg, stage), 'cannot run in wd',
        '%s %s (wd=%s)', pkg._id, pkg.scripts[stage], wd
      )
      return cb()
    }
 
    // set the env variables, then run scripts as a child process.
    var env = makeEnv(pkg)
    env.npm_lifecycle_event = stage
    env.npm_node_execpath = env.NODE = env.NODE || process.execPath
    env.npm_execpath = require.main.filename
 
    // 'nobody' typically doesn't have permission to write to /tmp
    // even if it's never used, sh freaks out.
    if (!npm.config.get('unsafe-perm')) env.TMPDIR = wd
 
    lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb)
  })
}
 
function _incorrectWorkingDirectory (wd, pkg) {
  return wd.lastIndexOf(pkg.name) !== wd.length - pkg.name.length
}
 
function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) {
  var pathArr = []
  var p = wd.split(/[\\\/]node_modules[\\\/]/)
  var acc = path.resolve(p.shift())
 
  p.forEach(function (pp) {
    pathArr.unshift(path.join(acc, 'node_modules', '.bin'))
    acc = path.join(acc, 'node_modules', pp)
  })
  pathArr.unshift(path.join(acc, 'node_modules', '.bin'))
 
  // we also unshift the bundled node-gyp-bin folder so that
  // the bundled one will be used for installing things.
  pathArr.unshift(path.join(__dirname, '..', '..', 'bin', 'node-gyp-bin'))
 
  if (shouldPrependCurrentNodeDirToPATH()) {
    // prefer current node interpreter in child scripts
    pathArr.push(path.dirname(process.execPath))
  }
 
  if (env[PATH]) pathArr.push(env[PATH])
  env[PATH] = pathArr.join(process.platform === 'win32' ? ';' : ':')
 
  var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)
 
  if (packageLifecycle) {
    // define this here so it's available to all scripts.
    env.npm_lifecycle_script = pkg.scripts[stage]
  } else {
    log.silly('lifecycle', logid(pkg, stage), 'no script for ' + stage + ', continuing')
  }
 
  function done (er) {
    if (er) {
      if (npm.config.get('force')) {
        log.info('lifecycle', logid(pkg, stage), 'forced, continuing', er)
        er = null
      } else if (failOk) {
        log.warn('lifecycle', logid(pkg, stage), 'continuing anyway', er.message)
        er = null
      }
    }
    cb(er)
  }
 
  chain(
    [
      packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe],
      [runHookLifecycle, pkg, env, wd, unsafe]
    ],
    done
  )
}
 
function shouldPrependCurrentNodeDirToPATH () {
  var cfgsetting = npm.config.get('scripts-prepend-node-path')
  if (cfgsetting === false) return false
  if (cfgsetting === true) return true
 
  var isDifferentNodeInPath
 
  var isWindows = process.platform === 'win32'
  var foundExecPath
  try {
    foundExecPath = which.sync(path.basename(process.execPath), {pathExt: isWindows ? ';' : ':'})
    // Apply `fs.realpath()` here to avoid false positives when `node` is a symlinked executable.
    isDifferentNodeInPath = fs.realpathSync(process.execPath).toUpperCase() !==
        fs.realpathSync(foundExecPath).toUpperCase()
  } catch (e) {
    isDifferentNodeInPath = true
  }
 
  if (cfgsetting === 'warn-only') {
    if (isDifferentNodeInPath && !shouldPrependCurrentNodeDirToPATH.hasWarned) {
      if (foundExecPath) {
        log.warn('lifecycle', 'The node binary used for scripts is', foundExecPath, 'but npm is using', process.execPath, 'itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.')
      } else {
        log.warn('lifecycle', 'npm is using', process.execPath, 'but there is no node binary in the current PATH. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.')
      }
      shouldPrependCurrentNodeDirToPATH.hasWarned = true
    }
 
    return false
  }
 
  return isDifferentNodeInPath
}
 
function validWd (d, cb) {
  fs.stat(d, function (er, st) {
    if (er || !st.isDirectory()) {
      var p = path.dirname(d)
      if (p === d) {
        return cb(new Error('Could not find suitable wd'))
      }
      return validWd(p, cb)
    }
    return cb(null, d)
  })
}
 
function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
  // run package lifecycle scripts in the package root, or the nearest parent.
  var stage = env.npm_lifecycle_event
  var cmd = env.npm_lifecycle_script
 
  var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd +
             '\n> ' + cmd + '\n'
  runCmd(note, cmd, pkg, env, stage, wd, unsafe, cb)
}
 
var running = false
var queue = []
function dequeue () {
  running = false
  if (queue.length) {
    var r = queue.shift()
    runCmd.apply(null, r)
  }
}
 
function runCmd (note, cmd, pkg, env, stage, wd, unsafe, cb) {
  if (running) {
    queue.push([note, cmd, pkg, env, stage, wd, unsafe, cb])
    return
  }
 
  running = true
  log.pause()
  var user = unsafe ? null : npm.config.get('user')
  var group = unsafe ? null : npm.config.get('group')
 
  if (log.level !== 'silent') {
    output(note)
  }
  log.verbose('lifecycle', logid(pkg, stage), 'unsafe-perm in lifecycle', unsafe)
 
  if (process.platform === 'win32') {
    unsafe = true
  }
 
  if (unsafe) {
    runCmd_(cmd, pkg, env, wd, stage, unsafe, 0, 0, cb)
  } else {
    uidNumber(user, group, function (er, uid, gid) {
      runCmd_(cmd, pkg, env, wd, stage, unsafe, uid, gid, cb)
    })
  }
}
 
function runCmd_ (cmd, pkg, env, wd, stage, unsafe, uid, gid, cb_) {
  function cb (er) {
    cb_.apply(null, arguments)
    log.resume()
    process.nextTick(dequeue)
  }
 
  var conf = {
    cwd: wd,
    env: env,
    stdio: [ 0, 1, 2 ]
  }
 
  if (!unsafe) {
    conf.uid = uid ^ 0
    conf.gid = gid ^ 0
  }
 
  var sh = 'sh'
  var shFlag = '-c'
 
  if (process.platform === 'win32') {
    sh = process.env.comspec || 'cmd'
    shFlag = '/d /s /c'
    conf.windowsVerbatimArguments = true
  }
 
  log.verbose('lifecycle', logid(pkg, stage), 'PATH:', env[PATH])
  log.verbose('lifecycle', logid(pkg, stage), 'CWD:', wd)
  log.silly('lifecycle', logid(pkg, stage), 'Args:', [shFlag, cmd])
 
  var proc = spawn(sh, [shFlag, cmd], conf)
 
  proc.on('error', procError)
  proc.on('close', function (code, signal) {
    log.silly('lifecycle', logid(pkg, stage), 'Returned: code:', code, ' signal:', signal)
    if (signal) {
      process.kill(process.pid, signal)
    } else if (code) {
      var er = new Error('Exit status ' + code)
      er.errno = code
    }
    procError(er)
  })
  process.once('SIGTERM', procKill)
  process.once('SIGINT', procInterupt)
 
  function procError (er) {
    if (er) {
      log.info('lifecycle', logid(pkg, stage), 'Failed to exec ' + stage + ' script')
      er.message = pkg._id + ' ' + stage + ': `' + cmd + '`\n' +
                   er.message
      if (er.code !== 'EPERM') {
        er.code = 'ELIFECYCLE'
      }
      fs.stat(npm.dir, function (statError, d) {
        if (statError && statError.code === 'ENOENT' && npm.dir.split(path.sep).slice(-1)[0] === 'node_modules') {
          log.warn('', 'Local package.json exists, but node_modules missing, did you mean to install?')
        }
      })
      er.pkgid = pkg._id
      er.stage = stage
      er.script = cmd
      er.pkgname = pkg.name
    }
    process.removeListener('SIGTERM', procKill)
    process.removeListener('SIGTERM', procInterupt)
    process.removeListener('SIGINT', procKill)
    return cb(er)
  }
  function procKill () {
    proc.kill()
  }
  function procInterupt () {
    proc.kill('SIGINT')
    proc.on('exit', function () {
      process.exit()
    })
    process.once('SIGINT', procKill)
  }
}
 
function runHookLifecycle (pkg, env, wd, unsafe, cb) {
  // check for a hook script, run if present.
  var stage = env.npm_lifecycle_event
  var hook = path.join(npm.dir, '.hooks', stage)
  var cmd = hook
 
  fs.stat(hook, function (er) {
    if (er) return cb()
    var note = '\n> ' + pkg._id + ' ' + stage + ' ' + wd +
               '\n> ' + cmd
    runCmd(note, hook, pkg, env, stage, wd, unsafe, cb)
  })
}
 
function makeEnv (data, prefix, env) {
  prefix = prefix || 'npm_package_'
  if (!env) {
    env = {}
    for (var i in process.env) {
      if (!i.match(/^npm_/)) {
        env[i] = process.env[i]
      }
    }
 
    // express and others respect the NODE_ENV value.
    if (npm.config.get('production')) env.NODE_ENV = 'production'
  } else if (!data.hasOwnProperty('_lifecycleEnv')) {
    Object.defineProperty(data, '_lifecycleEnv',
      {
        value: env,
        enumerable: false
      }
    )
  }
 
  for (i in data) {
    if (i.charAt(0) !== '_') {
      var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_')
      if (i === 'readme') {
        continue
      }
      if (data[i] && typeof data[i] === 'object') {
        try {
          // quick and dirty detection for cyclical structures
          JSON.stringify(data[i])
          makeEnv(data[i], envKey + '_', env)
        } catch (ex) {
          // usually these are package objects.
          // just get the path and basic details.
          var d = data[i]
          makeEnv(
            { name: d.name, version: d.version, path: d.path },
            envKey + '_',
            env
          )
        }
      } else {
        env[envKey] = String(data[i])
        env[envKey] = env[envKey].indexOf('\n') !== -1
                        ? JSON.stringify(env[envKey])
                        : env[envKey]
      }
    }
  }
 
  if (prefix !== 'npm_package_') return env
 
  prefix = 'npm_config_'
  var pkgConfig = {}
  var keys = npm.config.keys
  var pkgVerConfig = {}
  var namePref = data.name + ':'
  var verPref = data.name + '@' + data.version + ':'
 
  keys.forEach(function (i) {
    // in some rare cases (e.g. working with nerf darts), there are segmented
    // "private" (underscore-prefixed) config names -- don't export
    if (i.charAt(0) === '_' && i.indexOf('_' + namePref) !== 0 || i.match(/:_/)) {
      return
    }
    var value = npm.config.get(i)
    if (value instanceof Stream || Array.isArray(value)) return
    if (i.match(/umask/)) value = umask.toString(value)
    if (!value) value = ''
    else if (typeof value === 'number') value = '' + value
    else if (typeof value !== 'string') value = JSON.stringify(value)
 
    value = value.indexOf('\n') !== -1
          ? JSON.stringify(value)
          : value
    i = i.replace(/^_+/, '')
    var k
    if (i.indexOf(namePref) === 0) {
      k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, '_')
      pkgConfig[k] = value
    } else if (i.indexOf(verPref) === 0) {
      k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, '_')
      pkgVerConfig[k] = value
    }
    var envKey = (prefix + i).replace(/[^a-zA-Z0-9_]/g, '_')
    env[envKey] = value
  })
 
  prefix = 'npm_package_config_'
  ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
    for (var i in conf) {
      var envKey = (prefix + i)
      env[envKey] = conf[i]
    }
  })
 
  return env
}
 
function cmd (stage) {
  function CMD (args, cb) {
    npm.commands['run-script']([stage].concat(args), cb)
  }
  CMD.usage = usage(stage, 'npm ' + stage + ' [-- <args>]')
  var installedShallow = require('./completion/installed-shallow.js')
  CMD.completion = function (opts, cb) {
    installedShallow(opts, function (d) {
      return d.scripts && d.scripts[stage]
    }, cb)
  }
  return CMD
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/link.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/link.js

Statements: 24.49% (12 / 49)      Branches: 0% (0 / 22)      Functions: 0% (0 / 8)      Lines: 27.91% (12 / 43)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 751 1   1 1 1 1 1 1   1                                 1               1                   1                                                          
module.exports = link
link.ifExists = linkIfExists
 
var fs = require('graceful-fs')
var chain = require('slide').chain
var mkdir = require('mkdirp')
var rm = require('./gently-rm.js')
var path = require('path')
var npm = require('../npm.js')
 
function linkIfExists (from, to, gently, cb) {
  fs.stat(from, function (er) {
    if (er) return cb()
    fs.readlink(to, function (er, fromOnDisk) {
      // if the link already exists and matches what we would do,
      // we don't need to do anything
      if (!er) {
        var toDir = path.dirname(to)
        var absoluteFrom = path.resolve(toDir, from)
        var absoluteFromOnDisk = path.resolve(toDir, fromOnDisk)
        if (absoluteFrom === absoluteFromOnDisk) return cb()
      }
      link(from, to, gently, cb)
    })
  })
}
 
function resolveIfSymlink (maybeSymlinkPath, cb) {
  fs.lstat(maybeSymlinkPath, function (err, stat) {
    if (err) return cb.apply(this, arguments)
    if (!stat.isSymbolicLink()) return cb(null, maybeSymlinkPath)
    fs.readlink(maybeSymlinkPath, cb)
  })
}
 
function ensureFromIsNotSource (from, to, cb) {
  resolveIfSymlink(from, function (err, fromDestination) {
    if (err) return cb.apply(this, arguments)
    if (path.resolve(path.dirname(from), fromDestination) === path.resolve(to)) {
      return cb(new Error('Link target resolves to the same directory as link source: ' + to))
    }
    cb.apply(this, arguments)
  })
}
 
function link (from, to, gently, abs, cb) {
  if (typeof cb !== 'function') {
    cb = abs
    abs = false
  }
  if (typeof cb !== 'function') {
    cb = gently
    gently = null
  }
  if (npm.config.get('force')) gently = false
 
  to = path.resolve(to)
  var toDir = path.dirname(to)
  var absTarget = path.resolve(toDir, from)
  var relativeTarget = path.relative(toDir, absTarget)
  var target = abs ? absTarget : relativeTarget
 
  chain(
    [
      [ensureFromIsNotSource, absTarget, to],
      [fs, 'stat', absTarget],
      [rm, to, gently],
      [mkdir, path.dirname(to)],
      [fs, 'symlink', target, to, 'junction']
    ],
    cb
  )
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/locker.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/locker.js

Statements: 25.58% (11 / 43)      Branches: 0% (0 / 12)      Functions: 0% (0 / 6)      Lines: 26.83% (11 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 751 1   1 1   1 1   1   1                 1                                               1                                                 1          
var crypto = require('crypto')
var resolve = require('path').resolve
 
var lockfile = require('lockfile')
var log = require('npmlog')
 
var npm = require('../npm.js')
var correctMkdir = require('../utils/correct-mkdir.js')
 
var installLocks = {}
 
function lockFileName (base, name) {
  var c = name.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '')
  var p = resolve(base, name)
  var h = crypto.createHash('sha1').update(p).digest('hex')
  var l = resolve(npm.cache, '_locks')
 
  return resolve(l, c.substr(0, 24) + '-' + h.substr(0, 16) + '.lock')
}
 
function lock (base, name, cb) {
  var lockDir = resolve(npm.cache, '_locks')
  correctMkdir(lockDir, function (er) {
    if (er) return cb(er)
 
    var opts = {
      stale: npm.config.get('cache-lock-stale'),
      retries: npm.config.get('cache-lock-retries'),
      wait: npm.config.get('cache-lock-wait')
    }
    var lf = lockFileName(base, name)
    lockfile.lock(lf, opts, function (er) {
      if (er) log.warn('locking', lf, 'failed', er)
 
      if (!er) {
        log.verbose('lock', 'using', lf, 'for', resolve(base, name))
        installLocks[lf] = true
      }
 
      cb(er)
    })
  })
}
 
function unlock (base, name, cb) {
  var lf = lockFileName(base, name)
  var locked = installLocks[lf]
  if (locked === false) {
    return process.nextTick(cb)
  } else if (locked === true) {
    lockfile.unlock(lf, function (er) {
      if (er) {
        log.warn('unlocking', lf, 'failed', er)
      } else {
        installLocks[lf] = false
        log.verbose('unlock', 'done using', lf, 'for', resolve(base, name))
      }
 
      cb(er)
    })
  } else {
    var notLocked = new Error(
      'Attempt to unlock ' + resolve(base, name) + ", which hasn't been locked"
    )
    notLocked.code = 'ENOTLOCKED'
    throw notLocked
  }
}
 
module.exports = {
  lock: lock,
  unlock: unlock
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/map-to-registry.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/map-to-registry.js

Statements: 10.91% (6 / 55)      Branches: 0% (0 / 28)      Functions: 0% (0 / 2)      Lines: 11.11% (6 / 54)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 1021   1 1   1   1                                                                                                                 1                                                                          
var url = require('url')
 
var log = require('npmlog')
var npa = require('npm-package-arg')
 
module.exports = mapToRegistry
 
function mapToRegistry (name, config, cb) {
  log.silly('mapToRegistry', 'name', name)
  var registry
 
  // the name itself takes precedence
  var data = npa(name)
  if (data.scope) {
    // the name is definitely scoped, so escape now
    name = name.replace('/', '%2f')
 
    log.silly('mapToRegistry', 'scope (from package name)', data.scope)
 
    registry = config.get(data.scope + ':registry')
    if (!registry) {
      log.verbose('mapToRegistry', 'no registry URL found in name for scope', data.scope)
    }
  }
 
  // ...then --scope=@scope or --scope=scope
  var scope = config.get('scope')
  if (!registry && scope) {
    // I'm an enabler, sorry
    if (scope.charAt(0) !== '@') scope = '@' + scope
 
    log.silly('mapToRegistry', 'scope (from config)', scope)
 
    registry = config.get(scope + ':registry')
    if (!registry) {
      log.verbose('mapToRegistry', 'no registry URL found in config for scope', scope)
    }
  }
 
  // ...and finally use the default registry
  if (!registry) {
    log.silly('mapToRegistry', 'using default registry')
    registry = config.get('registry')
  }
 
  log.silly('mapToRegistry', 'registry', registry)
 
  var auth = config.getCredentialsByURI(registry)
 
  // normalize registry URL so resolution doesn't drop a piece of registry URL
  var normalized = registry.slice(-1) !== '/' ? registry + '/' : registry
  var uri
  log.silly('mapToRegistry', 'data', data)
  if (data.type === 'remote') {
    uri = data.spec
  } else {
    uri = url.resolve(normalized, name)
  }
 
  log.silly('mapToRegistry', 'uri', uri)
 
  cb(null, uri, scopeAuth(uri, registry, auth), normalized)
}
 
function scopeAuth (uri, registry, auth) {
  var cleaned = {
    scope: auth.scope,
    email: auth.email,
    alwaysAuth: auth.alwaysAuth,
    token: undefined,
    username: undefined,
    password: undefined,
    auth: undefined
  }
 
  var requestHost
  var registryHost
 
  if (auth.token || auth.auth || (auth.username && auth.password)) {
    requestHost = url.parse(uri).hostname
    registryHost = url.parse(registry).hostname
 
    if (requestHost === registryHost) {
      cleaned.token = auth.token
      cleaned.auth = auth.auth
      cleaned.username = auth.username
      cleaned.password = auth.password
    } else if (auth.alwaysAuth) {
      log.verbose('scopeAuth', 'alwaysAuth set for', registry)
      cleaned.token = auth.token
      cleaned.auth = auth.auth
      cleaned.username = auth.username
      cleaned.password = auth.password
    } else {
      log.silly('scopeAuth', uri, "doesn't share host with registry", registry)
    }
  }
 
  return cleaned
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/metrics.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/metrics.js

Statements: 28.89% (13 / 45)      Branches: 0% (0 / 18)      Functions: 0% (0 / 6)      Lines: 32.5% (13 / 40)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75  1 1 1 1   1 1 1 1   1   1             1         1                                                                 1                                
'use strict'
exports.start = startMetrics
exports.stop = stopMetrics
exports.save = saveMetrics
exports.send = sendMetrics
 
var fs = require('fs')
var path = require('path')
var npm = require('../npm.js')
var uuid = require('uuid')
 
var inMetrics = false
 
function startMetrics () {
  if (inMetrics) return
  // loaded on demand to avoid any recursive deps when `./metrics-launch` requires us.
  var metricsLaunch = require('./metrics-launch.js')
  npm.metricsProcess = metricsLaunch()
}
 
function stopMetrics () {
  if (inMetrics) return
  if (npm.metricsProcess) npm.metricsProcess.kill('SIGKILL')
}
 
function saveMetrics (itWorked) {
  if (inMetrics) return
  // If the metrics reporter hasn't managed to PUT yet then kill it so that it doesn't
  // step on our updating the anonymous-cli-metrics json
  stopMetrics()
  var metricsFile = path.join(npm.config.get('cache'), 'anonymous-cli-metrics.json')
  var metrics
  try {
    metrics = JSON.parse(fs.readFileSync(metricsFile))
    metrics.metrics.to = new Date().toISOString()
    if (itWorked) {
      ++metrics.metrics.successfulInstalls
    } else {
      ++metrics.metrics.failedInstalls
    }
  } catch (ex) {
    metrics = {
      metricId: uuid.v4(),
      metrics: {
        from: new Date().toISOString(),
        to: new Date().toISOString(),
        successfulInstalls: itWorked ? 1 : 0,
        failedInstalls: itWorked ? 0 : 1
      }
    }
  }
  try {
    fs.writeFileSync(metricsFile, JSON.stringify(metrics))
  } catch (ex) {
    // we couldn't write the error metrics file, um, well, oh well.
  }
}
 
function sendMetrics (metricsFile, metricsRegistry) {
  inMetrics = true
  var cliMetrics = JSON.parse(fs.readFileSync(metricsFile))
  npm.load({}, function (err) {
    if (err) return
    npm.registry.config.retry.retries = 0
    npm.registry.sendAnonymousCLIMetrics(metricsRegistry, cliMetrics, function (err) {
      if (err) {
        fs.writeFileSync(path.join(path.dirname(metricsFile), 'last-send-metrics-error.txt'), err.stack)
      } else {
        fs.unlinkSync(metricsFile)
      }
    })
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/module-name.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/module-name.js

Statements: 32.26% (10 / 31)      Branches: 0% (0 / 16)      Functions: 0% (0 / 3)      Lines: 40% (10 / 25)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35  1 1   1 1   1 1                 1 1       1 1                      
'use strict'
var path = require('path')
var validate = require('aproba')
 
module.exports = moduleName
module.exports.test = {}
 
module.exports.test.pathToPackageName = pathToPackageName
function pathToPackageName (dir) {
  if (dir == null) return ''
  if (dir === '') return ''
  var name = path.relative(path.resolve(dir, '..'), dir)
  var scoped = path.relative(path.resolve(dir, '../..'), dir)
  if (scoped[0] === '@') return scoped.replace(/\\/g, '/')
  return name
}
 
module.exports.test.isNotEmpty = isNotEmpty
function isNotEmpty (str) {
  return str != null && str !== ''
}
 
var unknown = 0
function moduleName (tree) {
  validate('O', arguments)
  var pkg = tree.package || tree
  if (isNotEmpty(pkg.name)) return pkg.name
  var pkgName = pathToPackageName(tree.path)
  if (pkgName !== '') return pkgName
  if (tree._invalidName != null) return tree._invalidName
  tree._invalidName = '!invalid#' + (++unknown)
  return tree._invalidName
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/no-progress-while-running.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/no-progress-while-running.js

Statements: 33.33% (6 / 18)      Branches: 0% (0 / 8)      Functions: 0% (0 / 4)      Lines: 40% (6 / 15)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/utils/ » no-progress-while-running.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25  1 1 1   1           1         1                
'use strict'
var log = require('npmlog')
var progressEnabled
var running = 0
 
var startRunning = exports.startRunning = function () {
  if (progressEnabled == null) progressEnabled = log.progressEnabled
  if (progressEnabled) log.disableProgress()
  ++running
}
 
var stopRunning = exports.stopRunning = function () {
  --running
  if (progressEnabled && running === 0) log.enableProgress()
}
 
exports.tillDone = function noProgressTillDone (cb) {
  startRunning()
  return function () {
    stopRunning()
    cb.apply(this, arguments)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/output.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/output.js

Statements: 40% (2 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 40% (2 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10  1   1            
'use strict'
var log = require('npmlog')
// output to stdout in a progress bar compatible way
module.exports = function () {
  log.clearProgress()
  console.log.apply(console, arguments)
  log.showProgress()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/package-id.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/package-id.js

Statements: 22.22% (2 / 9)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 25% (2 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  1   1                          
'use strict'
var moduleName = require('./module-name.js')
 
module.exports = function (tree) {
  var pkg = tree.package || tree
  // FIXME: Excluding the '@' here is cleaning up after the mess that
  // read-package-json makes. =(
  if (pkg._id && pkg._id !== '@') return pkg._id
  var name = moduleName(tree)
  if (pkg.version) {
    return name + '@' + pkg.version
  } else {
    return name
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/parse-json.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/parse-json.js

Statements: 63.64% (7 / 11)      Branches: 50% (1 / 2)      Functions: 66.67% (2 / 3)      Lines: 63.64% (7 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  1 1     1                 1 1       1     1      
'use strict'
var parseJSON = module.exports = function (content) {
  return JSON.parse(stripBOM(content))
}
 
parseJSON.noExceptions = function (content) {
  try {
    return parseJSON(content)
  } catch (ex) {
    return
  }
}
 
// from read-package-json
function stripBOM (content) {
  content = content.toString()
  // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  // because the buffer-to-string conversion in `fs.readFileSync()`
  // translates it to FEFF, the UTF-16 BOM.
  Iif (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1)
  }
  return content
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/pick-manifest-from-registry-metadata.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/pick-manifest-from-registry-metadata.js

Statements: 28.57% (4 / 14)      Branches: 0% (0 / 13)      Functions: 0% (0 / 1)      Lines: 28.57% (4 / 14)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/utils/ » pick-manifest-from-registry-metadata.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28  1   1 1   1                                          
'use strict'
module.exports = pickManifestFromRegistryMetadata
 
var log = require('npmlog')
var semver = require('semver')
 
function pickManifestFromRegistryMetadata (spec, tag, versions, metadata) {
  log.silly('pickManifestFromRegistryMetadata', 'spec', spec, 'tag', tag, 'versions', versions)
 
  // if the tagged version satisfies, then use that.
  var tagged = metadata['dist-tags'][tag]
  if (tagged &&
      metadata.versions[tagged] &&
      semver.satisfies(tagged, spec, true)) {
    return {resolvedTo: tag, manifest: metadata.versions[tagged]}
  }
  // find the max satisfying version.
  var ms = semver.maxSatisfying(versions, spec, true)
  if (ms) {
    return {resolvedTo: ms, manifest: metadata.versions[ms]}
  } else if (spec === '*' && versions.length && tagged && metadata.versions[tagged]) {
    return {resolvedTo: tag, manifest: metadata.versions[tagged]}
  } else {
    return
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/pulse-till-done.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/pulse-till-done.js

Statements: 33.33% (5 / 15)      Branches: 0% (0 / 6)      Functions: 0% (0 / 3)      Lines: 35.71% (5 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24  1 1   1 1   1                                
'use strict'
var validate = require('aproba')
var log = require('npmlog')
 
var pulsers = 0
var pulse
 
module.exports = function (prefix, cb) {
  validate('SF', [prefix, cb])
  if (!prefix) prefix = 'network'
  if (!pulsers++) {
    pulse = setInterval(function () {
      log.gauge.pulse(prefix)
    }, 250)
  }
  return function () {
    if (!--pulsers) {
      clearInterval(pulse)
    }
    cb.apply(null, arguments)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/read-local-package.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/read-local-package.js

Statements: 44.44% (4 / 9)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 50% (4 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 141   1 1   1                
exports = module.exports = readLocalPkg
 
var npm = require('../npm.js')
var readJson = require('read-package-json')
 
function readLocalPkg (cb) {
  if (npm.config.get('global')) return cb()
  var path = require('path')
  readJson(path.resolve(npm.prefix, 'package.json'), function (er, d) {
    return cb(er, d && d.name)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/spawn.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/spawn.js

Statements: 14.29% (6 / 42)      Branches: 0% (0 / 20)      Functions: 0% (0 / 5)      Lines: 17.65% (6 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521   1 1 1   1                   1                                                                      
module.exports = spawn
 
var _spawn = require('child_process').spawn
var EventEmitter = require('events').EventEmitter
var npwr = require('./no-progress-while-running.js')
 
function willCmdOutput (stdio) {
  if (stdio === 'inherit') return true
  if (!Array.isArray(stdio)) return false
  for (var fh = 1; fh <= 2; ++fh) {
    if (stdio[fh] === 'inherit') return true
    if (stdio[fh] === 1 || stdio[fh] === 2) return true
  }
  return false
}
 
function spawn (cmd, args, options) {
  var cmdWillOutput = willCmdOutput(options && options.stdio)
 
  if (cmdWillOutput) npwr.startRunning()
  var raw = _spawn(cmd, args, options)
  var cooked = new EventEmitter()
 
  raw.on('error', function (er) {
    if (cmdWillOutput) npwr.stopRunning()
    er.file = cmd
    cooked.emit('error', er)
  }).on('close', function (code, signal) {
    if (cmdWillOutput) npwr.stopRunning()
    // Create ENOENT error because Node.js v0.8 will not emit
    // an `error` event if the command could not be found.
    if (code === 127) {
      var er = new Error('spawn ENOENT')
      er.code = 'ENOENT'
      er.errno = 'ENOENT'
      er.syscall = 'spawn'
      er.file = cmd
      cooked.emit('error', er)
    } else {
      cooked.emit('close', code, signal)
    }
  })
 
  cooked.stdin = raw.stdin
  cooked.stdout = raw.stdout
  cooked.stderr = raw.stderr
  cooked.kill = function (sig) { return raw.kill(sig) }
 
  return cooked
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/tar.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/tar.js

Statements: 15.38% (38 / 247)      Branches: 2.9% (6 / 207)      Functions: 0% (0 / 35)      Lines: 18.1% (38 / 210)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455      1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1         1 1   1                                                   1     1   1                                                                                                                                                                                                       1   1 1                                                                                                                         1                                                   1                             1           1                                                   1                                                                                                                                                                                                                                                                               1                                
// commands for packing and unpacking tarballs
// this file is used by lib/cache.js
 
var fs = require('graceful-fs')
var path = require('path')
var writeFileAtomic = require('write-file-atomic')
var writeStreamAtomic = require('fs-write-stream-atomic')
var log = require('npmlog')
var uidNumber = require('uid-number')
var readJson = require('read-package-json')
var tar = require('tar')
var zlib = require('zlib')
var fstream = require('fstream')
var Packer = require('fstream-npm')
var iferr = require('iferr')
var inherits = require('inherits')
var npm = require('../npm.js')
var rm = require('./gently-rm.js')
var myUid = process.getuid && process.getuid()
var myGid = process.getgid && process.getgid()
var readPackageTree = require('read-package-tree')
var union = require('lodash.union')
var moduleName = require('./module-name.js')
var packageId = require('./package-id.js')
var pulseTillDone = require('../utils/pulse-till-done.js')
 
Iif (process.env.SUDO_UID && myUid === 0) {
  if (!isNaN(process.env.SUDO_UID)) myUid = +process.env.SUDO_UID
  if (!isNaN(process.env.SUDO_GID)) myGid = +process.env.SUDO_GID
}
 
exports.pack = pack
exports.unpack = unpack
 
function pack (tarball, folder, pkg, cb) {
  log.verbose('tar pack', [tarball, folder])
 
  log.verbose('tarball', tarball)
  log.verbose('folder', folder)
 
  readJson(path.join(folder, 'package.json'), function (er, pkg) {
    if (er || !pkg.bundleDependencies) {
      pack_(tarball, folder, null, pkg, cb)
    } else {
      // we require this at runtime due to load-order issues, because recursive
      // requires fail if you replace the exports object, and we do, not in deps, but
      // in a dep of it.
      var recalculateMetadata = require('../install/deps.js').recalculateMetadata
 
      readPackageTree(folder, pulseTillDone('pack:readTree:' + packageId(pkg), iferr(cb, function (tree) {
        var recalcGroup = log.newGroup('pack:recalc:' + packageId(pkg))
        recalculateMetadata(tree, recalcGroup, iferr(cb, function () {
          recalcGroup.finish()
          pack_(tarball, folder, tree, pkg, pulseTillDone('pack:' + packageId(pkg), cb))
        }))
      })))
    }
  })
}
 
function BundledPacker (props) {
  Packer.call(this, props)
}
inherits(BundledPacker, Packer)
 
BundledPacker.prototype.applyIgnores = function (entry, partial, entryObj) {
  if (!entryObj || entryObj.type !== 'Directory') {
    // package.json files can never be ignored.
    if (entry === 'package.json') return true
 
    // readme files should never be ignored.
    if (entry.match(/^readme(\.[^\.]*)$/i)) return true
 
    // license files should never be ignored.
    if (entry.match(/^(license|licence)(\.[^\.]*)?$/i)) return true
 
    // copyright notice files should never be ignored.
    if (entry.match(/^(notice)(\.[^\.]*)?$/i)) return true
 
    // changelogs should never be ignored.
    if (entry.match(/^(changes|changelog|history)(\.[^\.]*)?$/i)) return true
  }
 
  // special rules.  see below.
  if (entry === 'node_modules' && this.packageRoot) return true
 
  // package.json main file should never be ignored.
  var mainFile = this.package && this.package.main
  if (mainFile && path.resolve(this.path, entry) === path.resolve(this.path, mainFile)) return true
 
  // some files are *never* allowed under any circumstances
  // (VCS folders, native build cruft, npm cruft, regular cruft)
  if (entry === '.git' ||
      entry === 'CVS' ||
      entry === '.svn' ||
      entry === '.hg' ||
      entry === '.lock-wscript' ||
      entry.match(/^\.wafpickle-[0-9]+$/) ||
      (this.parent && this.parent.packageRoot && this.basename === 'build' &&
       entry === 'config.gypi') ||
      entry === 'npm-debug.log' ||
      entry === '.npmrc' ||
      entry.match(/^\..*\.swp$/) ||
      entry === '.DS_Store' ||
      entry.match(/^\._/) ||
      entry.match(/^.*\.orig$/)
    ) {
    return false
  }
 
  // in a node_modules folder, we only include bundled dependencies
  // also, prevent packages in node_modules from being affected
  // by rules set in the containing package, so that
  // bundles don't get busted.
  // Also, once in a bundle, everything is installed as-is
  // To prevent infinite cycles in the case of cyclic deps that are
  // linked with npm link, even in a bundle, deps are only bundled
  // if they're not already present at a higher level.
  if (this.bundleMagic) {
    // bubbling up.  stop here and allow anything the bundled pkg allows
    if (entry.charAt(0) === '@') {
      var firstSlash = entry.indexOf('/')
      // continue to list the packages in this scope
      if (firstSlash === -1) return true
 
      // bubbling up.  stop here and allow anything the bundled pkg allows
      if (entry.indexOf('/', firstSlash + 1) !== -1) return true
    // bubbling up.  stop here and allow anything the bundled pkg allows
    } else if (entry.indexOf('/') !== -1) {
      return true
    }
 
    // never include the .bin.  It's typically full of platform-specific
    // stuff like symlinks and .cmd files anyway.
    if (entry === '.bin') return false
 
    // the package root.
    var p = this.parent
    // the directory before this one.
    var pp = p && p.parent
    // the directory before that (if this is scoped)
    if (pp && pp.basename[0] === '@') pp = pp && pp.parent
 
    // if this entry has already been bundled, and is a symlink,
    // and it is the *same* symlink as this one, then exclude it.
    if (pp && pp.bundleLinks && this.bundleLinks &&
        pp.bundleLinks[entry] &&
        pp.bundleLinks[entry] === this.bundleLinks[entry]) {
      return false
    }
 
    // since it's *not* a symbolic link, if we're *already* in a bundle,
    // then we should include everything.
    if (pp && pp.package && pp.basename === 'node_modules') {
      return true
    }
 
    // only include it at this point if it's a bundleDependency
    return this.isBundled(entry)
  }
  // if (this.bundled) return true
 
  return Packer.prototype.applyIgnores.call(this, entry, partial, entryObj)
}
 
function nameMatch (name) { return function (other) { return name === moduleName(other) } }
 
function pack_ (tarball, folder, tree, pkg, cb) {
  function InstancePacker (props) {
    BundledPacker.call(this, props)
  }
  inherits(InstancePacker, BundledPacker)
  InstancePacker.prototype.isBundled = function (name) {
    var bd = this.package && this.package.bundleDependencies
    if (!bd) return false
 
    if (!Array.isArray(bd)) {
      throw new Error(packageId(this) + '\'s `bundledDependencies` should ' +
                      'be an array')
    }
    if (!tree) return false
 
    if (bd.indexOf(name) !== -1) return true
    var pkg = tree.children.filter(nameMatch(name))[0]
    if (!pkg) return false
    var requiredBy = [].concat(pkg.requiredBy)
    var seen = {}
    while (requiredBy.length) {
      var reqPkg = requiredBy.shift()
      if (seen[reqPkg.path]) continue
      seen[reqPkg.path] = true
      if (!reqPkg) continue
      if (reqPkg.parent === tree && bd.indexOf(moduleName(reqPkg)) !== -1) {
        return true
      }
      requiredBy = union(requiredBy, reqPkg.requiredBy)
    }
    return false
  }
 
  new InstancePacker({ path: folder, type: 'Directory', isDirectory: true })
    .on('error', function (er) {
      if (er) log.error('tar pack', 'Error reading ' + folder)
      return cb(er)
    })
 
    // By default, npm includes some proprietary attributes in the
    // package tarball.  This is sane, and allowed by the spec.
    // However, npm *itself* excludes these from its own package,
    // so that it can be more easily bootstrapped using old and
    // non-compliant tar implementations.
    .pipe(tar.Pack({ noProprietary: !npm.config.get('proprietary-attribs') }))
    .on('error', function (er) {
      if (er) log.error('tar.pack', 'tar creation error', tarball)
      cb(er)
    })
    .pipe(zlib.Gzip())
    .on('error', function (er) {
      if (er) log.error('tar.pack', 'gzip error ' + tarball)
      cb(er)
    })
    .pipe(writeStreamAtomic(tarball))
    .on('error', function (er) {
      if (er) log.error('tar.pack', 'Could not write ' + tarball)
      cb(er)
    })
    .on('close', cb)
}
 
function unpack (tarball, unpackTarget, dMode, fMode, uid, gid, cb) {
  log.verbose('tar', 'unpack', tarball)
  log.verbose('tar', 'unpacking to', unpackTarget)
  if (typeof cb !== 'function') {
    cb = gid
    gid = null
  }
  if (typeof cb !== 'function') {
    cb = uid
    uid = null
  }
  if (typeof cb !== 'function') {
    cb = fMode
    fMode = npm.modes.file
  }
  if (typeof cb !== 'function') {
    cb = dMode
    dMode = npm.modes.exec
  }
 
  uidNumber(uid, gid, function (er, uid, gid) {
    if (er) return cb(er)
    unpack_(tarball, unpackTarget, dMode, fMode, uid, gid, cb)
  })
}
 
function unpack_ (tarball, unpackTarget, dMode, fMode, uid, gid, cb) {
  rm(unpackTarget, function (er) {
    if (er) return cb(er)
    // gzip {tarball} --decompress --stdout \
    //   | tar -mvxpf - --strip-components=1 -C {unpackTarget}
    gunzTarPerm(tarball, unpackTarget,
                dMode, fMode,
                uid, gid,
                function (er, folder) {
                  if (er) return cb(er)
                  readJson(path.resolve(folder, 'package.json'), cb)
                })
  })
}
 
function gunzTarPerm (tarball, target, dMode, fMode, uid, gid, cb_) {
  if (!dMode) dMode = npm.modes.exec
  if (!fMode) fMode = npm.modes.file
  log.silly('gunzTarPerm', 'modes', [dMode.toString(8), fMode.toString(8)])
 
  var cbCalled = false
  function cb (er) {
    if (cbCalled) return
    cbCalled = true
    cb_(er, target)
  }
 
  var fst = fs.createReadStream(tarball)
 
  fst.on('open', function (fd) {
    fs.fstat(fd, function (er, st) {
      if (er) return fst.emit('error', er)
      if (st.size === 0) {
        er = new Error('0-byte tarball\n' +
                       'Please run `npm cache clean`')
        fst.emit('error', er)
      }
    })
  })
 
  // figure out who we're supposed to be, if we're not pretending
  // to be a specific user.
  if (npm.config.get('unsafe-perm') && process.platform !== 'win32') {
    uid = myUid
    gid = myGid
  }
 
  function extractEntry (entry) {
    log.silly('gunzTarPerm', 'extractEntry', entry.path)
    // never create things that are user-unreadable,
    // or dirs that are user-un-listable. Only leads to headaches.
    var originalMode = entry.mode = entry.mode || entry.props.mode
    entry.mode = entry.mode | (entry.type === 'Directory' ? dMode : fMode)
    entry.mode = entry.mode & (~npm.modes.umask)
    entry.props.mode = entry.mode
    if (originalMode !== entry.mode) {
      log.silly('gunzTarPerm', 'modified mode',
                [entry.path, originalMode, entry.mode])
    }
 
    // if there's a specific owner uid/gid that we want, then set that
    if (process.platform !== 'win32' &&
        typeof uid === 'number' &&
        typeof gid === 'number') {
      entry.props.uid = entry.uid = uid
      entry.props.gid = entry.gid = gid
    }
  }
 
  var extractOpts = { type: 'Directory', path: target, strip: 1 }
 
  if (process.platform !== 'win32' &&
      typeof uid === 'number' &&
      typeof gid === 'number') {
    extractOpts.uid = uid
    extractOpts.gid = gid
  }
 
  var sawIgnores = {}
  extractOpts.filter = function () {
    // symbolic links are not allowed in packages.
    if (this.type.match(/^.*Link$/)) {
      log.warn('excluding symbolic link',
               this.path.substr(target.length + 1) +
               ' -> ' + this.linkpath)
      return false
    }
 
    // Note: This mirrors logic in the fs read operations that are
    // employed during tarball creation, in the fstream-npm module.
    // It is duplicated here to handle tarballs that are created
    // using other means, such as system tar or git archive.
    if (this.type === 'File') {
      var base = path.basename(this.path)
      if (base === '.npmignore') {
        sawIgnores[ this.path ] = true
      } else if (base === '.gitignore') {
        var npmignore = this.path.replace(/\.gitignore$/, '.npmignore')
        if (sawIgnores[npmignore]) {
          // Skip this one, already seen.
          return false
        } else {
          // Rename, may be clobbered later.
          this.path = npmignore
          this._path = npmignore
        }
      }
    }
 
    return true
  }
 
  fst
    .on('error', function (er) {
      if (er) log.error('tar.unpack', 'error reading ' + tarball)
      cb(er)
    })
    .on('data', function OD (c) {
      // detect what it is.
      // Then, depending on that, we'll figure out whether it's
      // a single-file module, gzipped tarball, or naked tarball.
      // gzipped files all start with 1f8b08
      if (c[0] === 0x1F &&
          c[1] === 0x8B &&
          c[2] === 0x08) {
        fst
          .pipe(zlib.Unzip())
          .on('error', function (er) {
            if (er) log.error('tar.unpack', 'unzip error ' + tarball)
            cb(er)
          })
          .pipe(tar.Extract(extractOpts))
          .on('entry', extractEntry)
          .on('error', function (er) {
            if (er) log.error('tar.unpack', 'untar error ' + tarball)
            cb(er)
          })
          .on('close', cb)
      } else if (hasTarHeader(c)) {
        // naked tar
        fst
          .pipe(tar.Extract(extractOpts))
          .on('entry', extractEntry)
          .on('error', function (er) {
            if (er) log.error('tar.unpack', 'untar error ' + tarball)
            cb(er)
          })
          .on('close', cb)
      } else {
        // naked js file
        var jsOpts = { path: path.resolve(target, 'index.js') }
 
        if (process.platform !== 'win32' &&
            typeof uid === 'number' &&
            typeof gid === 'number') {
          jsOpts.uid = uid
          jsOpts.gid = gid
        }
 
        fst
          .pipe(fstream.Writer(jsOpts))
          .on('error', function (er) {
            if (er) log.error('tar.unpack', 'copy error ' + tarball)
            cb(er)
          })
          .on('close', function () {
            var j = path.resolve(target, 'package.json')
            readJson(j, function (er, d) {
              if (er) {
                log.error('not a package', tarball)
                return cb(er)
              }
              writeFileAtomic(j, JSON.stringify(d) + '\n', cb)
            })
          })
      }
 
      // now un-hook, and re-emit the chunk
      fst.removeListener('data', OD)
      fst.emit('data', c)
    })
}
 
function hasTarHeader (c) {
  return c[257] === 0x75 && // tar archives have 7573746172 at position
         c[258] === 0x73 && // 257 and 003030 or 202000 at position 262
         c[259] === 0x74 &&
         c[260] === 0x61 &&
         c[261] === 0x72 &&
 
       ((c[262] === 0x00 &&
         c[263] === 0x30 &&
         c[264] === 0x30) ||
 
        (c[262] === 0x20 &&
         c[263] === 0x20 &&
         c[264] === 0x00))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/temp-filename.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/temp-filename.js

Statements: 75% (3 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 75% (3 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9  1 1   1        
'use strict'
var uniqueFilename = require('unique-filename')
var npm = require('../npm.js')
 
module.exports = function (prefix) {
  return uniqueFilename(npm.tmp, prefix)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/umask.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/umask.js

Statements: 50% (5 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 50% (5 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 191 1 1   1     1                      
var umask = require('umask')
var npmlog = require('npmlog')
var _fromString = umask.fromString
 
module.exports = umask
 
// fromString with logging callback
umask.fromString = function (val) {
  _fromString(val, function (err, result) {
    if (err) {
      npmlog.warn('invalid umask', err.message)
    }
    val = result
  })
 
  return val
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/unsupported.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/unsupported.js

Statements: 47.62% (10 / 21)      Branches: 25% (1 / 4)      Functions: 66.67% (2 / 3)      Lines: 47.62% (10 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35  1 1 1   1 1 1           1 1 1               1                      
'use strict'
var semver = require('semver')
var supportedNode = '>= 4'
var knownBroken = '>=0.1 <=0.7'
 
var checkVersion = exports.checkVersion = function (version) {
  var versionNoPrerelease = version.replace(/-.*$/, '')
  return {
    broken: semver.satisfies(versionNoPrerelease, knownBroken),
    unsupported: !semver.satisfies(versionNoPrerelease, supportedNode)
  }
}
 
exports.checkForBrokenNode = function () {
  var nodejs = checkVersion(process.version)
  Iif (nodejs.broken) {
    console.error('ERROR: npm is known not to run on Node.js ' + process.version)
    console.error("You'll need to upgrade to a newer version in order to use this")
    console.error('version of npm. You can find the latest version at https://nodejs.org/')
    process.exit(1)
  }
}
 
exports.checkForUnsupportedNode = function () {
  var nodejs = checkVersion(process.version)
  if (nodejs.unsupported) {
    var log = require('npmlog')
    log.warn('npm', 'npm does not support Node.js ' + process.version)
    log.warn('npm', 'You should probably upgrade to a newer version of node as we')
    log.warn('npm', "can't make any promises that npm will work with this version.")
    log.warn('npm', 'You can find the latest version at https://nodejs.org/')
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/usage.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/usage.js

Statements: 100% (20 / 20)      Branches: 92.86% (13 / 14)      Functions: 100% (2 / 2)      Lines: 100% (17 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29  1   1 24 864 864 38     24   24 6 6 18 15 15     24 12 12     24      
'use strict'
var aliases = require('../config/cmd-list').aliases
 
module.exports = function usage (cmd, txt, opt) {
  var post = Object.keys(aliases).reduce(function (p, c) {
    var val = aliases[c]
    if (val !== cmd) return p
    return p.concat(c)
  }, [])
 
  if (opt || post.length > 0) txt += '\n\n'
 
  if (post.length === 1) {
    txt += 'alias: '
    txt += post.join(', ')
  } else if (post.length > 1) {
    txt += 'aliases: '
    txt += post.join(', ')
  }
 
  if (opt) {
    Eif (post.length > 0) txt += '\n'
    txt += 'common options: ' + opt
  }
 
  return txt
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/warn-deprecated.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/warn-deprecated.js

Statements: 31.25% (5 / 16)      Branches: 0% (0 / 8)      Functions: 25% (1 / 4)      Lines: 38.46% (5 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 251   1   1   1 1                                  
module.exports = warnDeprecated
 
var log = require('npmlog')
 
var deprecations = {}
 
function warnDeprecated (type) {
  return function warn (messages, instance) {
    if (!instance) {
      if (!deprecations[type]) {
        deprecations[type] = {}
        messages.forEach(function (m) { log.warn(type, m) })
      }
    } else {
      if (!deprecations[type]) deprecations[type] = {}
 
      if (!deprecations[type][instance]) {
        deprecations[type][instance] = true
        messages.forEach(function (m) { log.warn(type, m) })
      }
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/

Statements: 17.95% (21 / 117)      Branches: 0% (0 / 64)      Functions: 0% (0 / 27)      Lines: 19.63% (21 / 107)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/lib/utils/completion/
File Statements Branches Functions Lines
file-completion.js 23.53% (4 / 17) 0% (0 / 8) 0% (0 / 4) 26.67% (4 / 15)
installed-deep.js 18.92% (7 / 37) 0% (0 / 22) 0% (0 / 8) 20.59% (7 / 34)
installed-shallow.js 15.87% (10 / 63) 0% (0 / 34) 0% (0 / 15) 17.24% (10 / 58)
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/file-completion.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/file-completion.js

Statements: 23.53% (4 / 17)      Branches: 0% (0 / 8)      Functions: 0% (0 / 4)      Lines: 26.67% (4 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 261   1 1   1                                        
module.exports = fileCompletion
 
var mkdir = require('mkdirp')
var glob = require('glob')
 
function fileCompletion (root, req, depth, cb) {
  if (typeof cb !== 'function') {
    cb = depth
    depth = Infinity
  }
  mkdir(root, function (er) {
    if (er) return cb(er)
 
    // can be either exactly the req, or a descendent
    var pattern = root + '/{' + req + ',' + req + '/**/*}'
    var opts = { mark: true, dot: true, maxDepth: depth }
    glob(pattern, opts, function (er, files) {
      if (er) return cb(er)
      return cb(null, (files || []).map(function (f) {
        return f.substr(root.length + 1).replace(/^\/|\/$/g, '')
      }))
    })
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/installed-deep.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/installed-deep.js

Statements: 18.92% (7 / 37)      Branches: 0% (0 / 22)      Functions: 0% (0 / 8)      Lines: 20.59% (7 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541   1 1   1                                         1                     1       1                        
module.exports = installedDeep
 
var npm = require('../../npm.js')
var readInstalled = require('read-installed')
 
function installedDeep (opts, cb) {
  var local
  var global
  var depth = npm.config.get('depth')
  var opt = { depth: depth, dev: true }
 
  if (npm.config.get('global')) {
    local = []
    next()
  } else {
    readInstalled(npm.prefix, opt, function (er, data) {
      local = getNames(data || {})
      next()
    })
  }
 
  readInstalled(npm.config.get('prefix'), opt, function (er, data) {
    global = getNames(data || {})
    next()
  })
 
  function getNames_ (d, n) {
    if (d.realName && n) {
      if (n[d.realName]) return n
      n[d.realName] = true
    }
    if (!n) n = {}
    Object.keys(d.dependencies || {}).forEach(function (dep) {
      getNames_(d.dependencies[dep], n)
    })
    return n
  }
  function getNames (d) {
    return Object.keys(getNames_(d))
  }
 
  function next () {
    if (!local || !global) return
    if (!npm.config.get('global')) {
      global = global.map(function (g) {
        return [g, '-g']
      })
    }
    var names = local.concat(global)
    return cb(null, names)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/installed-shallow.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/lib/utils/completion/installed-shallow.js

Statements: 15.87% (10 / 63)      Branches: 0% (0 / 34)      Functions: 0% (0 / 15)      Lines: 17.24% (10 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89  1   1 1 1 1 1   1                                                           1           1                                                             1                        
 
module.exports = installedShallow
 
var npm = require('../../npm.js')
var fs = require('graceful-fs')
var path = require('path')
var readJson = require('read-package-json')
var asyncMap = require('slide').asyncMap
 
function installedShallow (opts, filter, cb) {
  if (typeof cb !== 'function') {
    cb = filter
    filter = null
  }
  var conf = opts.conf
  var args = conf.argv.remain
  if (args.length > 3) return cb()
  var local
  var global
  var localDir = npm.dir
  var globalDir = npm.globalDir
  if (npm.config.get('global')) {
    local = []
    next()
  } else {
    fs.readdir(localDir, function (er, pkgs) {
      local = (pkgs || []).filter(function (p) {
        return p.charAt(0) !== '.'
      })
      next()
    })
  }
 
  fs.readdir(globalDir, function (er, pkgs) {
    global = (pkgs || []).filter(function (p) {
      return p.charAt(0) !== '.'
    })
    next()
  })
  function next () {
    if (!local || !global) return
    filterInstalled(local, global, filter, cb)
  }
}
 
function filterInstalled (local, global, filter, cb) {
  var fl
  var fg
 
  if (!filter) {
    fl = local
    fg = global
    return next()
  }
 
  asyncMap(local, function (p, cb) {
    readJson(path.join(npm.dir, p, 'package.json'), function (er, d) {
      if (!d || !filter(d)) return cb(null, [])
      return cb(null, d.name)
    })
  }, function (er, local) {
    fl = local || []
    next()
  })
 
  var globalDir = npm.globalDir
  asyncMap(global, function (p, cb) {
    readJson(path.join(globalDir, p, 'package.json'), function (er, d) {
      if (!d || !filter(d)) return cb(null, [])
      return cb(null, d.name)
    })
  }, function (er, global) {
    fg = global || []
    next()
  })
 
  function next () {
    if (!fg || !fl) return
    if (!npm.config.get('global')) {
      fg = fg.map(function (g) {
        return [g, '-g']
      })
    }
    console.error('filtered', fl, fg)
    return cb(null, fl.concat(fg))
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/

Statements: 4.14% (7 / 169)      Branches: 1.69% (2 / 118)      Functions: 0% (0 / 16)      Lines: 4.43% (7 / 158)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/JSONStream/
File Statements Branches Functions Lines
index.js 4.14% (7 / 169) 1.69% (2 / 118) 0% (0 / 16) 4.43% (7 / 158)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/index.js

Statements: 4.14% (7 / 169)      Branches: 1.69% (2 / 118)      Functions: 0% (0 / 16)      Lines: 4.43% (7 / 158)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255        1                       1                                                                                                                                                                                                                                                                   1                             1                       1                                                                             1                                                                   1                
//#! /usr/bin/env node
 
'use strict'
 
var Parser = require('jsonparse')
  , through = require('through')
 
/*
 
  the value of this.stack that creationix's jsonparse has is weird.
 
  it makes this code ugly, but his problem is way harder that mine,
  so i'll forgive him.
 
*/
 
exports.parse = function (path, map) {
  var header, footer
  var parser = new Parser()
  var stream = through(function (chunk) {
    if('string' === typeof chunk)
      chunk = new Buffer(chunk)
    parser.write(chunk)
  },
  function (data) {
    if(data)
      stream.write(data)
    if (header)
        stream.emit('header', header)
    if (footer)
      stream.emit('footer', footer)
    stream.queue(null)
  })
 
  if('string' === typeof path)
    path = path.split('.').map(function (e) {
      if (e === '$*')
        return {emitKey: true}
      else if (e === '*')
        return true
      else if (e === '') // '..'.split('.') returns an empty string
        return {recurse: true}
      else
        return e
    })
 
 
  var count = 0, _key
  if(!path || !path.length)
    path = null
 
  parser.onValue = function (value) {
    if (!this.root)
      stream.root = value
 
    if(! path) return
 
    var i = 0 // iterates on path
    var j  = 0 // iterates on stack
    var emitKey = false;
    var emitPath = false;
    while (i < path.length) {
      var key = path[i]
      var c
      j++
 
      if (key && !key.recurse) {
        c = (j === this.stack.length) ? this : this.stack[j]
        if (!c) return
        if (! check(key, c.key)) {
          setHeaderFooter(c.key, value)
          return
        }
        emitKey = !!key.emitKey;
        emitPath = !!key.emitPath;
        i++
      } else {
        i++
        var nextKey = path[i]
        if (! nextKey) return
        while (true) {
          c = (j === this.stack.length) ? this : this.stack[j]
          if (!c) return
          if (check(nextKey, c.key)) {
            i++;
            if (!Object.isFrozen(this.stack[j]))
              this.stack[j].value = null
            break
          } else {
            setHeaderFooter(c.key, value)
          }
          j++
        }
      }
 
    }
 
    // emit header
    if (header) {
      stream.emit('header', header);
      header = false;
    }
    if (j !== this.stack.length) return
 
    count ++
    var actualPath = this.stack.slice(1).map(function(element) { return element.key }).concat([this.key])
    var data = this.value[this.key]
    if(null != data)
      if(null != (data = map ? map(data, actualPath) : data)) {
        if (emitKey || emitPath) {
          data = { value: data };
          if (emitKey)
            data["key"] = this.key;
          if (emitPath)
            data["path"] = actualPath;
        }
 
        stream.queue(data)
      }
    delete this.value[this.key]
    for(var k in this.stack)
      if (!Object.isFrozen(this.stack[k]))
        this.stack[k].value = null
  }
  parser._onToken = parser.onToken;
 
  parser.onToken = function (token, value) {
    parser._onToken(token, value);
    if (this.stack.length === 0) {
      if (stream.root) {
        if(!path)
          stream.queue(stream.root)
        count = 0;
        stream.root = null;
      }
    }
  }
 
  parser.onError = function (err) {
    if(err.message.indexOf("at position") > -1)
      err.message = "Invalid JSON (" + err.message + ")";
    stream.emit('error', err)
  }
 
  return stream
 
  function setHeaderFooter(key, value) {
    // header has not been emitted yet
    if (header !== false) {
      header = header || {}
      header[key] = value
    }
 
    // footer has not been emitted yet but header has
    if (footer !== false && header === false) {
      footer = footer || {}
      footer[key] = value
    }
  }
}
 
function check (x, y) {
  if ('string' === typeof x)
    return y == x
  else if (x && 'function' === typeof x.exec)
    return x.exec(y)
  else if ('boolean' === typeof x || 'object' === typeof x)
    return x
  else if ('function' === typeof x)
    return x(y)
  return false
}
 
exports.stringify = function (op, sep, cl, indent) {
  indent = indent || 0
  if (op === false){
    op = ''
    sep = '\n'
    cl = ''
  } else if (op == null) {
 
    op = '[\n'
    sep = '\n,\n'
    cl = '\n]\n'
 
  }
 
  //else, what ever you like
 
  var stream
    , first = true
    , anyData = false
  stream = through(function (data) {
    anyData = true
    try {
      var json = JSON.stringify(data, null, indent)
    } catch (err) {
      return stream.emit('error', err)
    }
    if(first) { first = false ; stream.queue(op + json)}
    else stream.queue(sep + json)
  },
  function (data) {
    if(!anyData)
      stream.queue(op)
    stream.queue(cl)
    stream.queue(null)
  })
 
  return stream
}
 
exports.stringifyObject = function (op, sep, cl, indent) {
  indent = indent || 0
  if (op === false){
    op = ''
    sep = '\n'
    cl = ''
  } else if (op == null) {
 
    op = '{\n'
    sep = '\n,\n'
    cl = '\n}\n'
 
  }
 
  //else, what ever you like
 
  var first = true
  var anyData = false
  var stream = through(function (data) {
    anyData = true
    var json = JSON.stringify(data[0]) + ':' + JSON.stringify(data[1], null, indent)
    if(first) { first = false ; this.queue(op + json)}
    else this.queue(sep + json)
  },
  function (data) {
    if(!anyData) this.queue(op)
    this.queue(cl)
 
    this.queue(null)
  })
 
  return stream
}
 
Iif(!module.parent && process.title !== 'browser') {
  process.stdin
    .pipe(exports.parse(process.argv[2]))
    .pipe(exports.stringify('[', ',\n', ']\n', 2))
    .pipe(process.stdout)
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/jsonparse/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/jsonparse/

Statements: 17.78% (61 / 343)      Branches: 0% (0 / 245)      Functions: 0% (0 / 14)      Lines: 21.48% (61 / 284)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/jsonparse/
File Statements Branches Functions Lines
jsonparse.js 17.78% (61 / 343) 0% (0 / 245) 0% (0 / 14) 21.48% (61 / 284)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js

Statements: 17.78% (61 / 343)      Branches: 0% (0 / 245)      Functions: 0% (0 / 14)      Lines: 21.48% (61 / 284)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402    1   1 1 1 1 1 1 1 1 1 1 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1 1   1 1   1 1 1 1 1 1 1   1   1                                           1                 1 1 1       1               1                                                     1                                                                                                                                                                                                                                                                                                                                                               1       1       1     1                 1       1     1                                                                                                                                         1   1    
/*global Buffer*/
// Named constants with unique integer values
var C = {};
// Tokens
var LEFT_BRACE    = C.LEFT_BRACE    = 0x1;
var RIGHT_BRACE   = C.RIGHT_BRACE   = 0x2;
var LEFT_BRACKET  = C.LEFT_BRACKET  = 0x3;
var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4;
var COLON         = C.COLON         = 0x5;
var COMMA         = C.COMMA         = 0x6;
var TRUE          = C.TRUE          = 0x7;
var FALSE         = C.FALSE         = 0x8;
var NULL          = C.NULL          = 0x9;
var STRING        = C.STRING        = 0xa;
var NUMBER        = C.NUMBER        = 0xb;
// Tokenizer States
var START   = C.START   = 0x11;
var STOP    = C.STOP    = 0x12;
var TRUE1   = C.TRUE1   = 0x21;
var TRUE2   = C.TRUE2   = 0x22;
var TRUE3   = C.TRUE3   = 0x23;
var FALSE1  = C.FALSE1  = 0x31;
var FALSE2  = C.FALSE2  = 0x32;
var FALSE3  = C.FALSE3  = 0x33;
var FALSE4  = C.FALSE4  = 0x34;
var NULL1   = C.NULL1   = 0x41;
var NULL2   = C.NULL2   = 0x42;
var NULL3   = C.NULL3   = 0x43;
var NUMBER1 = C.NUMBER1 = 0x51;
var NUMBER3 = C.NUMBER3 = 0x53;
var STRING1 = C.STRING1 = 0x61;
var STRING2 = C.STRING2 = 0x62;
var STRING3 = C.STRING3 = 0x63;
var STRING4 = C.STRING4 = 0x64;
var STRING5 = C.STRING5 = 0x65;
var STRING6 = C.STRING6 = 0x66;
// Parser States
var VALUE   = C.VALUE   = 0x71;
var KEY     = C.KEY     = 0x72;
// Parser Modes
var OBJECT  = C.OBJECT  = 0x81;
var ARRAY   = C.ARRAY   = 0x82;
// Character constants
var BACK_SLASH =      "\\".charCodeAt(0);
var FORWARD_SLASH =   "\/".charCodeAt(0);
var BACKSPACE =       "\b".charCodeAt(0);
var FORM_FEED =       "\f".charCodeAt(0);
var NEWLINE =         "\n".charCodeAt(0);
var CARRIAGE_RETURN = "\r".charCodeAt(0);
var TAB =             "\t".charCodeAt(0);
 
var STRING_BUFFER_SIZE = 64 * 1024;
 
function Parser() {
  this.tState = START;
  this.value = undefined;
 
  this.string = undefined; // string data
  this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE);
  this.stringBufferOffset = 0;
  this.unicode = undefined; // unicode escapes
 
  this.key = undefined;
  this.mode = undefined;
  this.stack = [];
  this.state = VALUE;
  this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary
  this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read
  this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached
 
  // Stream offset
  this.offset = -1;
}
 
// Slow code to string converter (only used when throwing syntax errors)
Parser.toknam = function (code) {
  var keys = Object.keys(C);
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i];
    if (C[key] === code) { return key; }
  }
  return code && ("0x" + code.toString(16));
};
 
var proto = Parser.prototype;
proto.onError = function (err) { throw err; };
proto.charError = function (buffer, i) {
  this.tState = STOP;
  this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState)));
};
proto.appendStringChar = function (char) {
  if (this.stringBufferOffset >= STRING_BUFFER_SIZE) {
    this.string += this.stringBuffer.toString('utf8');
    this.stringBufferOffset = 0;
  }
 
  this.stringBuffer[this.stringBufferOffset++] = char;
};
proto.appendStringBuf = function (buf, start, end) {
  var size = buf.length;
  if (typeof start === 'number') {
    if (typeof end === 'number') {
      if (end < 0) {
        // adding a negative end decreeses the size
        size = buf.length - start + end;
      } else {
        size = end - start;
      }
    } else {
      size = buf.length - start;
    }
  }
 
  if (size < 0) {
    size = 0;
  }
 
  if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) {
    this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);
    this.stringBufferOffset = 0;
  }
 
  buf.copy(this.stringBuffer, this.stringBufferOffset, start, end);
  this.stringBufferOffset += size;
};
proto.write = function (buffer) {
  if (typeof buffer === "string") buffer = new Buffer(buffer);
  var n;
  for (var i = 0, l = buffer.length; i < l; i++) {
    if (this.tState === START){
      n = buffer[i];
      this.offset++;
      if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // {
      }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // }
      }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [
      }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ]
      }else if(n === 0x3a){ this.onToken(COLON, ":");  // :
      }else if(n === 0x2c){ this.onToken(COMMA, ","); // ,
      }else if(n === 0x74){ this.tState = TRUE1;  // t
      }else if(n === 0x66){ this.tState = FALSE1;  // f
      }else if(n === 0x6e){ this.tState = NULL1; // n
      }else if(n === 0x22){ // "
        this.string = "";
        this.stringBufferOffset = 0;
        this.tState = STRING1;
      }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // -
      }else{
        if (n >= 0x30 && n < 0x40) { // 1-9
          this.string = String.fromCharCode(n); this.tState = NUMBER3;
        } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) {
          // whitespace
        } else {
          return this.charError(buffer, i);
        }
      }
    }else if (this.tState === STRING1){ // After open quote
      n = buffer[i]; // get current byte from buffer
      // check for carry over of a multi byte char split between data chunks
      // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration
      if (this.bytes_remaining > 0) {
        for (var j = 0; j < this.bytes_remaining; j++) {
          this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j];
        }
 
        this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]);
        this.bytes_in_sequence = this.bytes_remaining = 0;
        i = i + j - 1;
      } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time
        if (n <= 193 || n > 244) {
          return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState)));
        }
        if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;
        if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;
        if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;
        if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split
          for (var k = 0; k <= (buffer.length - 1 - i); k++) {
            this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk
          }
          this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length;
          i = buffer.length - 1;
        } else {
          this.appendStringBuf(buffer, i, i + this.bytes_in_sequence);
          i = i + this.bytes_in_sequence - 1;
        }
      } else if (n === 0x22) {
        this.tState = START;
        this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);
        this.stringBufferOffset = 0;
        this.onToken(STRING, this.string);
        this.offset += Buffer.byteLength(this.string, 'utf8') + 1;
        this.string = undefined;
      }
      else if (n === 0x5c) {
        this.tState = STRING2;
      }
      else if (n >= 0x20) { this.appendStringChar(n); }
      else {
          return this.charError(buffer, i);
      }
    }else if (this.tState === STRING2){ // After backslash
      n = buffer[i];
      if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1;
      }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1;
      }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1;
      }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1;
      }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1;
      }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1;
      }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1;
      }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1;
      }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3;
      }else{
        return this.charError(buffer, i);
      }
    }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes
      n = buffer[i];
      // 0-9 A-F a-f
      if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) {
        this.unicode += String.fromCharCode(n);
        if (this.tState++ === STRING6) {
          this.appendStringBuf(Buffer(String.fromCharCode(parseInt(this.unicode, 16))));
          this.unicode = undefined;
          this.tState = STRING1;
        }
      } else {
        return this.charError(buffer, i);
      }
    } else if (this.tState === NUMBER1 || this.tState === NUMBER3) {
        n = buffer[i];
 
        switch (n) {
          case 0x30: // 0
          case 0x31: // 1
          case 0x32: // 2
          case 0x33: // 3
          case 0x34: // 4
          case 0x35: // 5
          case 0x36: // 6
          case 0x37: // 7
          case 0x38: // 8
          case 0x39: // 9
          case 0x2e: // .
          case 0x65: // e
          case 0x45: // E
          case 0x2b: // +
          case 0x2d: // -
            this.string += String.fromCharCode(n);
            this.tState = NUMBER3;
            break;
          default:
            this.tState = START;
            var result = Number(this.string);
 
            if (isNaN(result)){
              return this.charError(buffer, i);
            }
 
            if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) {
              // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number
              this.onToken(STRING, this.string);
            } else {
              this.onToken(NUMBER, result);
            }
 
            this.offset += this.string.length - 1;
            this.string = undefined;
            i--;
            break;
        }
    }else if (this.tState === TRUE1){ // r
      if (buffer[i] === 0x72) { this.tState = TRUE2; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === TRUE2){ // u
      if (buffer[i] === 0x75) { this.tState = TRUE3; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === TRUE3){ // e
      if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === FALSE1){ // a
      if (buffer[i] === 0x61) { this.tState = FALSE2; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === FALSE2){ // l
      if (buffer[i] === 0x6c) { this.tState = FALSE3; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === FALSE3){ // s
      if (buffer[i] === 0x73) { this.tState = FALSE4; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === FALSE4){ // e
      if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === NULL1){ // u
      if (buffer[i] === 0x75) { this.tState = NULL2; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === NULL2){ // l
      if (buffer[i] === 0x6c) { this.tState = NULL3; }
      else { return this.charError(buffer, i); }
    }else if (this.tState === NULL3){ // l
      if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; }
      else { return this.charError(buffer, i); }
    }
  }
};
proto.onToken = function (token, value) {
  // Override this to get events
};
 
proto.parseError = function (token, value) {
  this.tState = STOP;
  this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state)));
};
proto.push = function () {
  this.stack.push({value: this.value, key: this.key, mode: this.mode});
};
proto.pop = function () {
  var value = this.value;
  var parent = this.stack.pop();
  this.value = parent.value;
  this.key = parent.key;
  this.mode = parent.mode;
  this.emit(value);
  if (!this.mode) { this.state = VALUE; }
};
proto.emit = function (value) {
  if (this.mode) { this.state = COMMA; }
  this.onValue(value);
};
proto.onValue = function (value) {
  // Override me
};
proto.onToken = function (token, value) {
  if(this.state === VALUE){
    if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){
      if (this.value) {
        this.value[this.key] = value;
      }
      this.emit(value);
    }else if(token === LEFT_BRACE){
      this.push();
      if (this.value) {
        this.value = this.value[this.key] = {};
      } else {
        this.value = {};
      }
      this.key = undefined;
      this.state = KEY;
      this.mode = OBJECT;
    }else if(token === LEFT_BRACKET){
      this.push();
      if (this.value) {
        this.value = this.value[this.key] = [];
      } else {
        this.value = [];
      }
      this.key = 0;
      this.mode = ARRAY;
      this.state = VALUE;
    }else if(token === RIGHT_BRACE){
      if (this.mode === OBJECT) {
        this.pop();
      } else {
        return this.parseError(token, value);
      }
    }else if(token === RIGHT_BRACKET){
      if (this.mode === ARRAY) {
        this.pop();
      } else {
        return this.parseError(token, value);
      }
    }else{
      return this.parseError(token, value);
    }
  }else if(this.state === KEY){
    if (token === STRING) {
      this.key = value;
      this.state = COLON;
    } else if (token === RIGHT_BRACE) {
      this.pop();
    } else {
      return this.parseError(token, value);
    }
  }else if(this.state === COLON){
    if (token === COLON) { this.state = VALUE; }
    else { return this.parseError(token, value); }
  }else if(this.state === COMMA){
    if (token === COMMA) {
      if (this.mode === ARRAY) { this.key++; this.state = VALUE; }
      else if (this.mode === OBJECT) { this.state = KEY; }
 
    } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) {
      this.pop();
    } else {
      return this.parseError(token, value);
    }
  }else{
    return this.parseError(token, value);
  }
};
 
Parser.C = C;
 
module.exports = Parser;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/through/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/through/

Statements: 8.45% (6 / 71)      Branches: 0% (0 / 34)      Functions: 0% (0 / 13)      Lines: 9.52% (6 / 63)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/through/
File Statements Branches Functions Lines
index.js 8.45% (6 / 71) 0% (0 / 34) 0% (0 / 13) 9.52% (6 / 63)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/through/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/JSONStream/node_modules/through/index.js

Statements: 8.45% (6 / 71)      Branches: 0% (0 / 34)      Functions: 0% (0 / 13)      Lines: 9.52% (6 / 63)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 1101             1 1       1                                 1                                                                 1                                                                                              
var Stream = require('stream')
 
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
 
exports = module.exports = through
through.through = through
 
//create a readable writable stream.
 
function through (write, end, opts) {
  write = write || function (data) { this.queue(data) }
  end = end || function () { this.queue(null) }
 
  var ended = false, destroyed = false, buffer = [], _ended = false
  var stream = new Stream()
  stream.readable = stream.writable = true
  stream.paused = false
 
//  stream.autoPause   = !(opts && opts.autoPause   === false)
  stream.autoDestroy = !(opts && opts.autoDestroy === false)
 
  stream.write = function (data) {
    write.call(this, data)
    return !stream.paused
  }
 
  function drain() {
    while(buffer.length && !stream.paused) {
      var data = buffer.shift()
      if(null === data)
        return stream.emit('end')
      else
        stream.emit('data', data)
    }
  }
 
  stream.queue = stream.push = function (data) {
//    console.error(ended)
    if(_ended) return stream
    if(data === null) _ended = true
    buffer.push(data)
    drain()
    return stream
  }
 
  //this will be registered as the first 'end' listener
  //must call destroy next tick, to make sure we're after any
  //stream piped from here.
  //this is only a problem if end is not emitted synchronously.
  //a nicer way to do this is to make sure this is the last listener for 'end'
 
  stream.on('end', function () {
    stream.readable = false
    if(!stream.writable && stream.autoDestroy)
      process.nextTick(function () {
        stream.destroy()
      })
  })
 
  function _end () {
    stream.writable = false
    end.call(stream)
    if(!stream.readable && stream.autoDestroy)
      stream.destroy()
  }
 
  stream.end = function (data) {
    if(ended) return
    ended = true
    if(arguments.length) stream.write(data)
    _end() // will emit or queue
    return stream
  }
 
  stream.destroy = function () {
    if(destroyed) return
    destroyed = true
    ended = true
    buffer.length = 0
    stream.writable = stream.readable = false
    stream.emit('close')
    return stream
  }
 
  stream.pause = function () {
    if(stream.paused) return
    stream.paused = true
    return stream
  }
 
  stream.resume = function () {
    if(stream.paused) {
      stream.paused = false
      stream.emit('resume')
    }
    drain()
    //may have become paused again,
    //as drain emits 'data'.
    if(!stream.paused)
      stream.emit('drain')
    return stream
  }
  return stream
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/abbrev/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/abbrev/

Statements: 85.71% (30 / 35)      Branches: 91.67% (22 / 24)      Functions: 40% (2 / 5)      Lines: 85.29% (29 / 34)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/abbrev/
File Statements Branches Functions Lines
abbrev.js 85.71% (30 / 35) 91.67% (22 / 24) 40% (2 / 5) 85.29% (29 / 34)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/abbrev/abbrev.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/abbrev/abbrev.js

Statements: 85.71% (30 / 35)      Branches: 91.67% (22 / 24)      Functions: 40% (2 / 5)      Lines: 85.29% (29 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631   1   1                       1 1     1 87       1     1   1 87       87 86 254 254 254 254 71 71     86 86 27 27   59 243 243     1     1 471      
module.exports = exports = abbrev.abbrev = abbrev
 
abbrev.monkeyPatch = monkeyPatch
 
function monkeyPatch () {
  Object.defineProperty(Array.prototype, 'abbrev', {
    value: function () { return abbrev(this) },
    enumerable: false, configurable: true, writable: true
  })
 
  Object.defineProperty(Object.prototype, 'abbrev', {
    value: function () { return abbrev(Object.keys(this)) },
    enumerable: false, configurable: true, writable: true
  })
}
 
function abbrev (list) {
  Iif (arguments.length !== 1 || !Array.isArray(list)) {
    list = Array.prototype.slice.call(arguments, 0)
  }
  for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
    args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
  }
 
  // sort them lexicographically, so that they're next to their nearest kin
  args = args.sort(lexSort)
 
  // walk through each, seeing how much it has in common with the next and previous
  var abbrevs = {}
    , prev = ""
  for (var i = 0, l = args.length ; i < l ; i ++) {
    var current = args[i]
      , next = args[i + 1] || ""
      , nextMatches = true
      , prevMatches = true
    if (current === next) continue
    for (var j = 0, cl = current.length ; j < cl ; j ++) {
      var curChar = current.charAt(j)
      nextMatches = nextMatches && curChar === next.charAt(j)
      prevMatches = prevMatches && curChar === prev.charAt(j)
      if (!nextMatches && !prevMatches) {
        j ++
        break
      }
    }
    prev = current
    if (j === cl) {
      abbrevs[current] = current
      continue
    }
    for (var a = current.substr(0, j) ; j <= cl ; j ++) {
      abbrevs[a] = current
      a += current.charAt(j)
    }
  }
  return abbrevs
}
 
function lexSort (a, b) {
  return a === b ? 0 : a > b ? 1 : -1
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansi-regex/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansi-regex/

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (1 / 1)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/ansi-regex/
File Statements Branches Functions Lines
index.js 100% (2 / 2) 100% (0 / 0) 100% (1 / 1) 100% (2 / 2)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansi-regex/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansi-regex/index.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (1 / 1)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6  1 1      
'use strict';
module.exports = function () {
	return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansicolors/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansicolors/

Statements: 85.71% (12 / 14)      Branches: 100% (0 / 0)      Functions: 50% (2 / 4)      Lines: 85.71% (12 / 14)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/ansicolors/
File Statements Branches Functions Lines
ansicolors.js 85.71% (12 / 14) 100% (0 / 0) 50% (2 / 4) 85.71% (12 / 14)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansicolors/ansicolors.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansicolors/ansicolors.js

Statements: 85.71% (12 / 14)      Branches: 100% (0 / 0)      Functions: 50% (2 / 4)      Lines: 85.71% (12 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67      1                                                                                 1 16 16   16         1 16 16   16         1 1 1    
// ColorCodes explained: http://www.termsys.demon.co.uk/vtansi.htm
'use strict';
 
var colorNums = {
      white         :  37
    , black         :  30
    , blue          :  34
    , cyan          :  36
    , green         :  32
    , magenta       :  35
    , red           :  31
    , yellow        :  33
    , brightBlack   :  90
    , brightRed     :  91
    , brightGreen   :  92
    , brightYellow  :  93
    , brightBlue    :  94
    , brightMagenta :  95
    , brightCyan    :  96
    , brightWhite   :  97
    }
  , backgroundColorNums = {
      bgBlack         :  40
    , bgRed           :  41
    , bgGreen         :  42
    , bgYellow        :  43
    , bgBlue          :  44
    , bgMagenta       :  45
    , bgCyan          :  46
    , bgWhite         :  47
    , bgBrightBlack   :  100
    , bgBrightRed     :  101
    , bgBrightGreen   :  102
    , bgBrightYellow  :  103
    , bgBrightBlue    :  104
    , bgBrightMagenta :  105
    , bgBrightCyan    :  106
    , bgBrightWhite   :  107
    } 
  , open   =  {}
  , close  =  {}
  , colors =  {}
  ;
 
Object.keys(colorNums).forEach(function (k) {
  var o =  open[k]  =  '\u001b[' + colorNums[k] + 'm';
  var c =  close[k] =  '\u001b[39m';
 
  colors[k] = function (s) { 
    return o + s + c;
  };
});
 
Object.keys(backgroundColorNums).forEach(function (k) {
  var o =  open[k]  =  '\u001b[' + backgroundColorNums[k] + 'm';
  var c =  close[k] =  '\u001b[49m';
 
  colors[k] = function (s) { 
    return o + s + c;
  };
});
 
module.exports =  colors;
colors.open    =  open;
colors.close   =  close;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansistyles/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansistyles/

Statements: 66.67% (4 / 6)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 66.67% (4 / 6)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/ansistyles/
File Statements Branches Functions Lines
ansistyles.js 66.67% (4 / 6) 100% (0 / 0) 50% (1 / 2) 66.67% (4 / 6)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansistyles/ansistyles.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ansistyles/ansistyles.js

Statements: 66.67% (4 / 6)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 66.67% (4 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40                                  1                       1 7             1    
'use strict';
 
/*
 * Info: http://www.termsys.demon.co.uk/vtansi.htm#colors 
 * Following caveats
 * bright    - brightens the color (bold-blue is same as brigthtBlue)
 * dim       - nothing on Mac or Linux
 * italic    - nothing on Mac or Linux
 * underline - underlines string
 * blink     - nothing on Mac or linux
 * inverse   - background becomes foreground and vice versa
 *
 * In summary, the only styles that work are:
 *  - bright, underline and inverse
 *  - the others are only included for completeness
 */
 
var styleNums = {
    reset     :  [0, 22]
  , bright    :  [1, 22]
  , dim       :  [2, 22]
  , italic    :  [3, 23]
  , underline :  [4, 24]
  , blink     :  [5, 25]
  , inverse   :  [7, 27]
  }
  , styles = {}
  ;
 
Object.keys(styleNums).forEach(function (k) {
  styles[k] = function (s) { 
    var open = styleNums[k][0]
      , close = styleNums[k][1];
    return '\u001b[' + open + 'm' + s + '\u001b[' + close + 'm';
  };
});
 
module.exports = styles;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/aproba/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/aproba/

Statements: 53.75% (43 / 80)      Branches: 56.41% (22 / 39)      Functions: 40% (10 / 25)      Lines: 60.87% (42 / 69)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/aproba/
File Statements Branches Functions Lines
index.js 53.75% (43 / 80) 56.41% (22 / 39) 40% (10 / 25) 60.87% (42 / 69)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/aproba/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/aproba/index.js

Statements: 53.75% (43 / 80)      Branches: 56.41% (22 / 39)      Functions: 40% (10 / 25)      Lines: 60.87% (42 / 69)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105    1 1     1   3 1 1   1   1       1 1 1 1 1 1 1 1 1 1 1   1 1 3 3   1 1 1           1 1     1 3 3 3 3   3           3       1       1       1                 1       1               1         1              
'use strict'
 
function isArguments (thingy) {
  return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee')
}
 
var types = {
  '*': {label: 'any', check: function () { return true }},
  A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }},
  S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }},
  N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }},
  F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }},
  O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }},
  B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }},
  E: {label: 'error', check: function (thingy) { return thingy instanceof Error }},
  Z: {label: 'null', check: function (thingy) { return thingy == null }}
}
 
var validate = module.exports = function (rawSchemas, args) {
  Iif (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length)
  Iif (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas')
  Iif (!args) throw missingRequiredArg(1, 'args')
  Iif (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas)
  Iif (!types.A.check(args)) throw invalidType(1, ['array'], args)
  var schemas = rawSchemas.split('|')
  var arity = {}
  function addSchema (schema) {
    var group = arity[schema.length] = arity[schema.length] || []
    Eif (group.indexOf(schema) === -1) group.push(schema)
  }
  schemas.forEach(function (schema) {
    for (var ii = 0; ii < schema.length; ++ii) {
      var type = schema[ii]
      Iif (!types[type]) throw unknownType(ii, type)
    }
    Iif (/E.*E/.test(schema)) throw moreThanOneError(schema)
    addSchema(schema)
    Iif (/E/.test(schema)) {
      addSchema(schema.replace(/E.*$/, 'E'))
      addSchema(schema.replace(/E/, 'Z'))
      if (schema.length === 1) addSchema('')
    }
  })
  var matching = arity[args.length]
  Iif (!matching) {
    throw wrongNumberOfArgs(Object.keys(arity), args.length)
  }
  for (var ii = 0; ii < args.length; ++ii) {
    var newMatching = matching.filter(function (schema) {
      var type = schema[ii]
      var typeCheck = types[type].check
      return typeCheck(args[ii])
    })
    Iif (!newMatching.length) {
      var labels = matching.map(function (schema) {
        return types[schema[ii]].label
      }).filter(function (schema) { return schema != null })
      throw invalidType(ii, labels, args[ii])
    }
    matching = newMatching
  }
}
 
function missingRequiredArg (num) {
  return newException('EMISSINGARG', 'Missing required argument #' + (num + 1))
}
 
function unknownType (num, type) {
  return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1))
}
 
function invalidType (num, expectedTypes, value) {
  var valueType
  Object.keys(types).forEach(function (typeCode) {
    if (types[typeCode].check(value)) valueType = types[typeCode].label
  })
  return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' +
    englishList(expectedTypes) + ' but got ' + valueType)
}
 
function englishList (list) {
  return list.join(', ').replace(/, ([^,]+)$/, ' or $1')
}
 
function wrongNumberOfArgs (expected, got) {
  var english = englishList(expected)
  var args = expected.every(function (ex) { return ex.length === 1 })
    ? 'argument'
    : 'arguments'
  return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got)
}
 
function moreThanOneError (schema) {
  return newException('ETOOMANYERRORTYPES',
    'Only one error type per argument signature is allowed, more than one found in "' + schema + '"')
}
 
function newException (code, msg) {
  var e = new Error(msg)
  e.code = code
  Error.captureStackTrace(e, validate)
  return e
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/archy/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/archy/

Statements: 5.56% (1 / 18)      Branches: 0% (0 / 22)      Functions: 0% (0 / 3)      Lines: 6.67% (1 / 15)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/archy/
File Statements Branches Functions Lines
index.js 5.56% (1 / 18) 0% (0 / 22) 0% (0 / 3) 6.67% (1 / 15)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/archy/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/archy/index.js

Statements: 5.56% (1 / 18)      Branches: 0% (0 / 22)      Functions: 0% (0 / 3)      Lines: 6.67% (1 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 371                                                                        
module.exports = function archy (obj, prefix, opts) {
    if (prefix === undefined) prefix = '';
    if (!opts) opts = {};
    var chr = function (s) {
        var chars = {
            '│' : '|',
            '└' : '`',
            '├' : '+',
            '─' : '-',
            '┬' : '-'
        };
        return opts.unicode === false ? chars[s] : s;
    };
    
    if (typeof obj === 'string') obj = { label : obj };
    
    var nodes = obj.nodes || [];
    var lines = (obj.label || '').split('\n');
    var splitter = '\n' + prefix + (nodes.length ? chr('│') : ' ') + ' ';
    
    return prefix
        + lines.join(splitter) + '\n'
        + nodes.map(function (node, ix) {
            var last = ix === nodes.length - 1;
            var more = node.nodes && node.nodes.length;
            var prefix_ = prefix + (last ? ' ' : chr('│')) + ' ';
            
            return prefix
                + (last ? chr('└') : chr('├')) + chr('─')
                + (more ? chr('┬') : chr('─')) + ' '
                + archy(node, prefix_, opts).slice(prefix.length + 2)
            ;
        }).join('')
    ;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/asap/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/asap/

Statements: 26.15% (17 / 65)      Branches: 0% (0 / 22)      Functions: 0% (0 / 6)      Lines: 26.15% (17 / 65)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/asap/
File Statements Branches Functions Lines
asap.js 21.43% (6 / 28) 0% (0 / 8) 0% (0 / 3) 21.43% (6 / 28)
raw.js 29.73% (11 / 37) 0% (0 / 14) 0% (0 / 3) 29.73% (11 / 37)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/asap/asap.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/asap/asap.js

Statements: 21.43% (6 / 28)      Branches: 0% (0 / 8)      Functions: 0% (0 / 3)      Lines: 21.43% (6 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67    1 1                       1 1                       1         1                                                                  
"use strict";
 
var rawAsap = require("./raw");
var freeTasks = [];
 
/**
 * Calls a task as soon as possible after returning, in its own event, with
 * priority over IO events. An exception thrown in a task can be handled by
 * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise
 * crash the process. If the error is handled, all subsequent tasks will
 * resume.
 *
 * @param {{call}} task A callable object, typically a function that takes no
 * arguments.
 */
module.exports = asap;
function asap(task) {
    var rawTask;
    if (freeTasks.length) {
        rawTask = freeTasks.pop();
    } else {
        rawTask = new RawTask();
    }
    rawTask.task = task;
    rawTask.domain = process.domain;
    rawAsap(rawTask);
}
 
function RawTask() {
    this.task = null;
    this.domain = null;
}
 
RawTask.prototype.call = function () {
    if (this.domain) {
        this.domain.enter();
    }
    var threw = true;
    try {
        this.task.call();
        threw = false;
        // If the task throws an exception (presumably) Node.js restores the
        // domain stack for the next event.
        if (this.domain) {
            this.domain.exit();
        }
    } finally {
        // We use try/finally and a threw flag to avoid messing up stack traces
        // when we catch and release errors.
        if (threw) {
            // In Node.js, uncaught exceptions are considered fatal errors.
            // Re-throw them to interrupt flushing!
            // Ensure that flushing continues if an uncaught exception is
            // suppressed listening process.on("uncaughtException") or
            // domain.on("error").
            rawAsap.requestFlush();
        }
        // If the task threw an error, we do not want to exit the domain here.
        // Exiting the domain would prevent the domain from catching the error.
        this.task = null;
        this.domain = null;
        freeTasks.push(this);
    }
};
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/asap/raw.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/asap/raw.js

Statements: 29.73% (11 / 37)      Branches: 0% (0 / 14)      Functions: 0% (0 / 3)      Lines: 29.73% (11 / 37)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103    1 1                     1 1                 1     1       1       1               1                                                     1 1                                                              
"use strict";
 
var domain; // The domain module is executed on demand
var hasSetImmediate = typeof setImmediate === "function";
 
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including network IO events in Node.js.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
    if (!queue.length) {
        requestFlush();
        flushing = true;
    }
    // Avoids a function call
    queue[queue.length] = task;
}
 
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory excaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
 
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
    while (index < queue.length) {
        var currentIndex = index;
        // Advance the index before calling the task. This ensures that we will
        // begin flushing on the next task the task throws an error.
        index = index + 1;
        queue[currentIndex].call();
        // Prevent leaking memory for long chains of recursive calls to `asap`.
        // If we call `asap` within tasks scheduled by `asap`, the queue will
        // grow, but to avoid an O(n) walk for every task we execute, we don't
        // shift tasks off the queue after they have been executed.
        // Instead, we periodically shift 1024 tasks off the queue.
        if (index > capacity) {
            // Manually shift all values starting at the index back to the
            // beginning of the queue.
            for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
                queue[scan] = queue[scan + index];
            }
            queue.length -= index;
            index = 0;
        }
    }
    queue.length = 0;
    index = 0;
    flushing = false;
}
 
rawAsap.requestFlush = requestFlush;
function requestFlush() {
    // Ensure flushing is not bound to any domain.
    // It is not sufficient to exit the domain, because domains exist on a stack.
    // To execute code outside of any domain, the following dance is necessary.
    var parentDomain = process.domain;
    if (parentDomain) {
        if (!domain) {
            // Lazy execute the domain module.
            // Only employed if the user elects to use domains.
            domain = require("domain");
        }
        domain.active = process.domain = null;
    }
 
    // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
    // cannot handle recursion.
    // `requestFlush` will only be called recursively from `asap.js`, to resume
    // flushing after an error is thrown into a domain.
    // Conveniently, `setImmediate` was introduced in the same version
    // `process.nextTick` started throwing recursion errors.
    if (flushing && hasSetImmediate) {
        setImmediate(flush);
    } else {
        process.nextTick(flush);
    }
 
    if (parentDomain) {
        domain.active = process.domain = parentDomain;
    }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/call-limit/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/call-limit/

Statements: 12.07% (7 / 58)      Branches: 0% (0 / 20)      Functions: 0% (0 / 12)      Lines: 12.5% (7 / 56)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/call-limit/
File Statements Branches Functions Lines
call-limit.js 12.07% (7 / 58) 0% (0 / 20) 0% (0 / 12) 12.5% (7 / 56)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/call-limit/call-limit.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/call-limit/call-limit.js

Statements: 12.07% (7 / 58)      Branches: 0% (0 / 20)      Functions: 0% (0 / 12)      Lines: 12.5% (7 / 56)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88    1   1                                                       1                   1                           1                   1                     1                    
"use strict"
 
var defaultMaxRunning = 50
 
var limit = module.exports = function (func, maxRunning) {
  var running = 0
  var queue = []
  if (!maxRunning) maxRunning = defaultMaxRunning
  return function limited () {
    var self = this
    var args = Array.prototype.slice.call(arguments)
    if (running >= maxRunning) {
      queue.push({self: this, args: args})
      return
    }
    var cb = typeof args[args.length-1] === 'function' && args.pop()
    ++ running
    args.push(function () {
      var cbargs = arguments
      -- running
      cb && process.nextTick(function () {
        cb.apply(self, cbargs)
      })
      if (queue.length) {
        var next = queue.shift()
        limited.apply(next.self, next.args)
      }
    })
    func.apply(self, args)
  }
}
 
module.exports.method = function (classOrObj, method, maxRunning) {
  if (typeof classOrObj === 'function') {
    var func = classOrObj.prototype[method]
    classOrObj.prototype[method] = limit(func, maxRunning)
  } else {
    var func = classOrObj[method]
    classOrObj[method] = limit(func, maxRunning)
  }
}
 
module.exports.promise = function (func, maxRunning) {
  var running = 0
  var queue = []
  if (!maxRunning) maxRunning = defaultMaxRunning
  return function () {
    var self = this
    var args = Array.prototype.slice.call(arguments)
    return new Promise(function (resolve) {
      if (running >= maxRunning) {
        queue.push({self: self, args: args, resolve: resolve})
        return
      } else {
        runNext(self, args, resolve)
      }
      function runNext (self, args, resolve) {
        ++ running
        resolve(
          func.apply(self, args)
          .then(finish, function (err) {
            finish(err)
            throw err
           }))
      }
 
      function finish () {
        -- running
        if (queue.length) {
          var next = queue.shift()
          process.nextTick(runNext, next.self, next.args, next.resolve)
        }
      }
    })
  }
}
 
module.exports.promise.method = function (classOrObj, method, maxRunning) {
  if (typeof classOrObj === 'function') {
    var func = classOrObj.prototype[method]
    classOrObj.prototype[method] = limit.promise(func, maxRunning)
  } else {
    var func = classOrObj[method]
    classOrObj[method] = limit.promise(func, maxRunning)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/chownr/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/chownr/

Statements: 15% (6 / 40)      Branches: 0% (0 / 26)      Functions: 0% (0 / 7)      Lines: 18.18% (6 / 33)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/chownr/
File Statements Branches Functions Lines
chownr.js 15% (6 / 40) 0% (0 / 26) 0% (0 / 7) 18.18% (6 / 33)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/chownr/chownr.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/chownr/chownr.js

Statements: 15% (6 / 40)      Branches: 0% (0 / 26)      Functions: 0% (0 / 7)      Lines: 18.18% (6 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541 1   1     1                                       1               1                                      
module.exports = chownr
chownr.sync = chownrSync
 
var fs = require("fs")
, path = require("path")
 
function chownr (p, uid, gid, cb) {
  fs.readdir(p, function (er, children) {
    // any error other than ENOTDIR means it's not readable, or
    // doesn't exist.  give up.
    if (er && er.code !== "ENOTDIR") return cb(er)
    if (er || !children.length) return fs.chown(p, uid, gid, cb)
 
    var len = children.length
    , errState = null
    children.forEach(function (child) {
      var pathChild = path.resolve(p, child);
      fs.lstat(pathChild, function(er, stats) {
        if (er)
          return cb(er)
        if (!stats.isSymbolicLink())
          chownr(pathChild, uid, gid, then)
        else
          then()
        })
    })
    function then (er) {
      if (errState) return
      if (er) return cb(errState = er)
      if (-- len === 0) return fs.chown(p, uid, gid, cb)
    }
  })
}
 
function chownrSync (p, uid, gid) {
  var children
  try {
    children = fs.readdirSync(p)
  } catch (er) {
    if (er && er.code === "ENOTDIR") return fs.chownSync(p, uid, gid)
    throw er
  }
  if (!children.length) return fs.chownSync(p, uid, gid)
 
  children.forEach(function (child) {
    var pathChild = path.resolve(p, child)
    var stats = fs.lstatSync(pathChild)
    if (!stats.isSymbolicLink())
      chownrSync(pathChild, uid, gid)
  })
  return fs.chownSync(p, uid, gid)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/cmd-shim/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/cmd-shim/

Statements: 18.67% (14 / 75)      Branches: 0% (0 / 28)      Functions: 0% (0 / 16)      Lines: 19.44% (14 / 72)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/cmd-shim/
File Statements Branches Functions Lines
index.js 18.67% (14 / 75) 0% (0 / 28) 0% (0 / 16) 19.44% (14 / 72)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/cmd-shim/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/cmd-shim/index.js

Statements: 18.67% (14 / 75)      Branches: 0% (0 / 28)      Functions: 0% (0 / 16)      Lines: 19.44% (14 / 72)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182                    1 1   1   1       1                 1           1                 1         1         1                                       1                                                                                                                                                                         1         1           1                        
// On windows, create a .cmd file.
// Read the #! in the file to see what it uses.  The vast majority
// of the time, this will be either:
// "#!/usr/bin/env <prog> <args...>"
// or:
// "#!<prog> <args...>"
//
// Write a binroot/pkg.bin + ".cmd" file that has this line in it:
// @<prog> <args...> %~dp0<target> %*
 
module.exports = cmdShim
cmdShim.ifExists = cmdShimIfExists
 
var fs = require("graceful-fs")
 
var mkdir = require("mkdirp")
  , path = require("path")
  , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/
 
function cmdShimIfExists (from, to, cb) {
  fs.stat(from, function (er) {
    if (er) return cb()
    cmdShim(from, to, cb)
  })
}
 
// Try to unlink, but ignore errors.
// Any problems will surface later.
function rm (path, cb) {
  fs.unlink(path, function(er) {
    cb()
  })
}
 
function cmdShim (from, to, cb) {
  fs.stat(from, function (er, stat) {
    if (er)
      return cb(er)
 
    cmdShim_(from, to, cb)
  })
}
 
function cmdShim_ (from, to, cb) {
  var then = times(2, next, cb)
  rm(to, then)
  rm(to + ".cmd", then)
 
  function next(er) {
    writeShim(from, to, cb)
  }
}
 
function writeShim (from, to, cb) {
  // make a cmd file and a sh script
  // First, check if the bin is a #! of some sort.
  // If not, then assume it's something that'll be compiled, or some other
  // sort of script, and just call it directly.
  mkdir(path.dirname(to), function (er) {
    if (er)
      return cb(er)
    fs.readFile(from, "utf8", function (er, data) {
      if (er) return writeShim_(from, to, null, null, cb)
      var firstLine = data.trim().split(/\r*\n/)[0]
        , shebang = firstLine.match(shebangExpr)
      if (!shebang) return writeShim_(from, to, null, null, cb)
      var prog = shebang[1]
        , args = shebang[2] || ""
      return writeShim_(from, to, prog, args, cb)
    })
  })
}
 
function writeShim_ (from, to, prog, args, cb) {
  var shTarget = path.relative(path.dirname(to), from)
    , target = shTarget.split("/").join("\\")
    , longProg
    , shProg = prog && prog.split("\\").join("/")
    , shLongProg
  shTarget = shTarget.split("\\").join("/")
  args = args || ""
  if (!prog) {
    prog = "\"%~dp0\\" + target + "\""
    shProg = "\"$basedir/" + shTarget + "\""
    args = ""
    target = ""
    shTarget = ""
  } else {
    longProg = "\"%~dp0\\" + prog + ".exe\""
    shLongProg = "\"$basedir/" + prog + "\""
    target = "\"%~dp0\\" + target + "\""
    shTarget = "\"$basedir/" + shTarget + "\""
  }
 
  // @IF EXIST "%~dp0\node.exe" (
  //   "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %*
  // ) ELSE (
  //   SETLOCAL
  //   SET PATHEXT=%PATHEXT:;.JS;=;%
  //   node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %*
  // )
  var cmd
  if (longProg) {
    cmd = "@IF EXIST " + longProg + " (\r\n"
        + "  " + longProg + " " + args + " " + target + " %*\r\n"
        + ") ELSE (\r\n"
        + "  @SETLOCAL\r\n"
        + "  @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n"
        + "  " + prog + " " + args + " " + target + " %*\r\n"
        + ")"
  } else {
    cmd = "@" + prog + " " + args + " " + target + " %*\r\n"
  }
 
  // #!/bin/sh
  // basedir=`dirname "$0"`
  //
  // case `uname` in
  //     *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
  // esac
  //
  // if [ -x "$basedir/node.exe" ]; then
  //   "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@"
  //   ret=$?
  // else
  //   node "$basedir/node_modules/npm/bin/npm-cli.js" "$@"
  //   ret=$?
  // fi
  // exit $ret
 
  var sh = "#!/bin/sh\n"
 
  if (shLongProg) {
    sh = sh
        + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n"
        + "\n"
        + "case `uname` in\n"
        + "    *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;\n"
        + "esac\n"
        + "\n"
 
    sh = sh
       + "if [ -x "+shLongProg+" ]; then\n"
       + "  " + shLongProg + " " + args + " " + shTarget + " \"$@\"\n"
       + "  ret=$?\n"
       + "else \n"
       + "  " + shProg + " " + args + " " + shTarget + " \"$@\"\n"
       + "  ret=$?\n"
       + "fi\n"
       + "exit $ret\n"
  } else {
    sh = shProg + " " + args + " " + shTarget + " \"$@\"\n"
       + "exit $?\n"
  }
 
  var then = times(2, next, cb)
  fs.writeFile(to + ".cmd", cmd, "utf8", then)
  fs.writeFile(to, sh, "utf8", then)
  function next () {
    chmodShim(to, cb)
  }
}
 
function chmodShim (to, cb) {
  var then = times(2, cb, cb)
  fs.chmod(to, 0755, then)
  fs.chmod(to + ".cmd", 0755, then)
}
 
function times(n, ok, cb) {
  var errState = null
  return function(er) {
    if (!errState) {
      if (er)
        cb(errState = er)
      else if (--n === 0)
        ok()
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/

Statements: 13.16% (35 / 266)      Branches: 0% (0 / 126)      Functions: 0% (0 / 49)      Lines: 14.29% (35 / 245)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/columnify/
File Statements Branches Functions Lines
columnify.js 9.55% (17 / 178) 0% (0 / 88) 0% (0 / 36) 10.56% (17 / 161)
utils.js 17.86% (15 / 84) 0% (0 / 38) 0% (0 / 12) 18.75% (15 / 80)
width.js 75% (3 / 4) 100% (0 / 0) 0% (0 / 1) 75% (3 / 4)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/columnify.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/columnify.js

Statements: 9.55% (17 / 178)      Branches: 0% (0 / 88)      Functions: 0% (0 / 36)      Lines: 10.56% (17 / 161)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310    1   1   1 1 1 1 1 1   1       1       1                         1                                                                                                                                                                                                                                                                                                                                                                       1                                                             1             1                                                                         1             1                          
"use strict";
 
var wcwidth = require('./width');
 
var _require = require('./utils');
 
var padRight = _require.padRight;
var padCenter = _require.padCenter;
var padLeft = _require.padLeft;
var splitIntoLines = _require.splitIntoLines;
var splitLongWords = _require.splitLongWords;
var truncateString = _require.truncateString;
 
var DEFAULT_HEADING_TRANSFORM = function DEFAULT_HEADING_TRANSFORM(key) {
  return key.toUpperCase();
};
 
var DEFAULT_DATA_TRANSFORM = function DEFAULT_DATA_TRANSFORM(cell, column, index) {
  return cell;
};
 
var DEFAULTS = Object.freeze({
  maxWidth: Infinity,
  minWidth: 0,
  columnSplitter: ' ',
  truncate: false,
  truncateMarker: '…',
  preserveNewLines: false,
  paddingChr: ' ',
  showHeaders: true,
  headingTransform: DEFAULT_HEADING_TRANSFORM,
  dataTransform: DEFAULT_DATA_TRANSFORM
});
 
module.exports = function (items) {
  var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
 
  var columnConfigs = options.config || {};
  delete options.config; // remove config so doesn't appear on every column.
 
  var maxLineWidth = options.maxLineWidth || Infinity;
  if (maxLineWidth === 'auto') maxLineWidth = process.stdout.columns || Infinity;
  delete options.maxLineWidth; // this is a line control option, don't pass it to column
 
  // Option defaults inheritance:
  // options.config[columnName] => options => DEFAULTS
  options = mixin({}, DEFAULTS, options);
 
  options.config = options.config || Object.create(null);
 
  options.spacing = options.spacing || '\n'; // probably useless
  options.preserveNewLines = !!options.preserveNewLines;
  options.showHeaders = !!options.showHeaders;
  options.columns = options.columns || options.include; // alias include/columns, prefer columns if supplied
  var columnNames = options.columns || []; // optional user-supplied columns to include
 
  items = toArray(items, columnNames);
 
  // if not suppled column names, automatically determine columns from data keys
  if (!columnNames.length) {
    items.forEach(function (item) {
      for (var columnName in item) {
        if (columnNames.indexOf(columnName) === -1) columnNames.push(columnName);
      }
    });
  }
 
  // initialize column defaults (each column inherits from options.config)
  var columns = columnNames.reduce(function (columns, columnName) {
    var column = Object.create(options);
    columns[columnName] = mixin(column, columnConfigs[columnName]);
    return columns;
  }, Object.create(null));
 
  // sanitize column settings
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    column.name = columnName;
    column.maxWidth = Math.ceil(column.maxWidth);
    column.minWidth = Math.ceil(column.minWidth);
    column.truncate = !!column.truncate;
    column.align = column.align || 'left';
  });
 
  // sanitize data
  items = items.map(function (item) {
    var result = Object.create(null);
    columnNames.forEach(function (columnName) {
      // null/undefined -> ''
      result[columnName] = item[columnName] != null ? item[columnName] : '';
      // toString everything
      result[columnName] = '' + result[columnName];
      if (columns[columnName].preserveNewLines) {
        // merge non-newline whitespace chars
        result[columnName] = result[columnName].replace(/[^\S\n]/gmi, ' ');
      } else {
        // merge all whitespace chars
        result[columnName] = result[columnName].replace(/\s/gmi, ' ');
      }
    });
    return result;
  });
 
  // transform data cells
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    items = items.map(function (item, index) {
      var col = Object.create(column);
      item[columnName] = column.dataTransform(item[columnName], col, index);
 
      var changedKeys = Object.keys(col);
      // disable default heading transform if we wrote to column.name
      if (changedKeys.indexOf('name') !== -1) {
        if (column.headingTransform !== DEFAULT_HEADING_TRANSFORM) return;
        column.headingTransform = function (heading) {
          return heading;
        };
      }
      changedKeys.forEach(function (key) {
        return column[key] = col[key];
      });
      return item;
    });
  });
 
  // add headers
  var headers = {};
  if (options.showHeaders) {
    columnNames.forEach(function (columnName) {
      var column = columns[columnName];
 
      if (!column.showHeaders) {
        headers[columnName] = '';
        return;
      }
 
      headers[columnName] = column.headingTransform(column.name);
    });
    items.unshift(headers);
  }
  // get actual max-width between min & max
  // based on length of data in columns
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    column.width = items.map(function (item) {
      return item[columnName];
    }).reduce(function (min, cur) {
      // if already at maxWidth don't bother testing
      if (min >= column.maxWidth) return min;
      return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
    }, 0);
  });
 
  // split long words so they can break onto multiple lines
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    items = items.map(function (item) {
      item[columnName] = splitLongWords(item[columnName], column.width, column.truncateMarker);
      return item;
    });
  });
 
  // wrap long lines. each item is now an array of lines.
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    items = items.map(function (item, index) {
      var cell = item[columnName];
      item[columnName] = splitIntoLines(cell, column.width);
 
      // if truncating required, only include first line + add truncation char
      if (column.truncate && item[columnName].length > 1) {
        item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker));
        var firstLine = item[columnName][0];
        if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker;
        item[columnName] = item[columnName].slice(0, 1);
      }
      return item;
    });
  });
 
  // recalculate column widths from truncated output/lines
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    column.width = items.map(function (item) {
      return item[columnName].reduce(function (min, cur) {
        if (min >= column.maxWidth) return min;
        return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
      }, 0);
    }).reduce(function (min, cur) {
      if (min >= column.maxWidth) return min;
      return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, cur)));
    }, 0);
  });
 
  var rows = createRows(items, columns, columnNames, options.paddingChr); // merge lines into rows
  // conceive output
  return rows.reduce(function (output, row) {
    return output.concat(row.reduce(function (rowOut, line) {
      return rowOut.concat(line.join(options.columnSplitter));
    }, []));
  }, []).map(function (line) {
    return truncateString(line, maxLineWidth);
  }).join(options.spacing);
};
 
/**
 * Convert wrapped lines into rows with padded values.
 *
 * @param Array items data to process
 * @param Array columns column width settings for wrapping
 * @param Array columnNames column ordering
 * @return Array items wrapped in arrays, corresponding to lines
 */
 
function createRows(items, columns, columnNames, paddingChr) {
  return items.map(function (item) {
    var row = [];
    var numLines = 0;
    columnNames.forEach(function (columnName) {
      numLines = Math.max(numLines, item[columnName].length);
    });
    // combine matching lines of each rows
 
    var _loop = function _loop(i) {
      row[i] = row[i] || [];
      columnNames.forEach(function (columnName) {
        var column = columns[columnName];
        var val = item[columnName][i] || ''; // || '' ensures empty columns get padded
        if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr));else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr));else row[i].push(padRight(val, column.width, paddingChr));
      });
    };
 
    for (var i = 0; i < numLines; i++) {
      _loop(i);
    }
    return row;
  });
}
 
/**
 * Object.assign
 *
 * @return Object Object with properties mixed in.
 */
 
function mixin() {
  var _Object;
 
  if (Object.assign) return (_Object = Object).assign.apply(_Object, arguments);
  return ObjectAssign.apply(undefined, arguments);
}
 
function ObjectAssign(target, firstSource) {
  "use strict";
 
  if (target === undefined || target === null) throw new TypeError("Cannot convert first argument to object");
 
  var to = Object(target);
 
  var hasPendingException = false;
  var pendingException;
 
  for (var i = 1; i < arguments.length; i++) {
    var nextSource = arguments[i];
    if (nextSource === undefined || nextSource === null) continue;
 
    var keysArray = Object.keys(Object(nextSource));
    for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
      var nextKey = keysArray[nextIndex];
      try {
        var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
        if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
      } catch (e) {
        if (!hasPendingException) {
          hasPendingException = true;
          pendingException = e;
        }
      }
    }
 
    if (hasPendingException) throw pendingException;
  }
  return to;
}
 
/**
 * Adapted from String.prototype.endsWith polyfill.
 */
 
function endsWith(target, searchString, position) {
  position = position || target.length;
  position = position - searchString.length;
  var lastIndex = target.lastIndexOf(searchString);
  return lastIndex !== -1 && lastIndex === position;
}
 
function toArray(items, columnNames) {
  if (Array.isArray(items)) return items;
  var rows = [];
  for (var key in items) {
    var item = {};
    item[columnNames[0] || 'key'] = key;
    item[columnNames[1] || 'value'] = items[key];
    rows.push(item);
  }
  return rows;
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/utils.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/utils.js

Statements: 17.86% (15 / 84)      Branches: 0% (0 / 38)      Functions: 0% (0 / 12)      Lines: 18.75% (15 / 80)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195    1                 1                           1                                   1                                       1                                 1 1                                                         1                                                                                                       1                                                 1 1 1 1 1 1    
"use strict"
 
var wcwidth = require('./width')
 
/**
 * repeat string `str` up to total length of `len`
 *
 * @param String str string to repeat
 * @param Number len total length of output string
 */
 
function repeatString(str, len) {
  return Array.apply(null, {length: len + 1}).join(str).slice(0, len)
}
 
/**
 * Pad `str` up to total length `max` with `chr`.
 * If `str` is longer than `max`, padRight will return `str` unaltered.
 *
 * @param String str string to pad
 * @param Number max total length of output string
 * @param String chr optional. Character to pad with. default: ' '
 * @return String padded str
 */
 
function padRight(str, max, chr) {
  str = str != null ? str : ''
  str = String(str)
  var length = max - wcwidth(str)
  if (length <= 0) return str
  return str + repeatString(chr || ' ', length)
}
 
/**
 * Pad `str` up to total length `max` with `chr`.
 * If `str` is longer than `max`, padCenter will return `str` unaltered.
 *
 * @param String str string to pad
 * @param Number max total length of output string
 * @param String chr optional. Character to pad with. default: ' '
 * @return String padded str
 */
 
function padCenter(str, max, chr) {
  str = str != null ? str : ''
  str = String(str)
  var length = max - wcwidth(str)
  if (length <= 0) return str
  var lengthLeft = Math.floor(length/2)
  var lengthRight = length - lengthLeft
  return repeatString(chr || ' ', lengthLeft) + str + repeatString(chr || ' ', lengthRight)
}
 
/**
 * Pad `str` up to total length `max` with `chr`, on the left.
 * If `str` is longer than `max`, padRight will return `str` unaltered.
 *
 * @param String str string to pad
 * @param Number max total length of output string
 * @param String chr optional. Character to pad with. default: ' '
 * @return String padded str
 */
 
function padLeft(str, max, chr) {
  str = str != null ? str : ''
  str = String(str)
  var length = max - wcwidth(str)
  if (length <= 0) return str
  return repeatString(chr || ' ', length) + str
}
 
/**
 * Split a String `str` into lines of maxiumum length `max`.
 * Splits on word boundaries. Preserves existing new lines.
 *
 * @param String str string to split
 * @param Number max length of each line
 * @return Array Array containing lines.
 */
 
function splitIntoLines(str, max) {
  function _splitIntoLines(str, max) {
    return str.trim().split(' ').reduce(function(lines, word) {
      var line = lines[lines.length - 1]
      if (line && wcwidth(line.join(' ')) + wcwidth(word) < max) {
        lines[lines.length - 1].push(word) // add to line
      }
      else lines.push([word]) // new line
      return lines
    }, []).map(function(l) {
      return l.join(' ')
    })
  }
  return str.split('\n').map(function(str) {
    return _splitIntoLines(str, max)
  }).reduce(function(lines, line) {
    return lines.concat(line)
  }, [])
}
 
/**
 * Add spaces and `truncationChar` between words of
 * `str` which are longer than `max`.
 *
 * @param String str string to split
 * @param Number max length of each line
 * @param Number truncationChar character to append to split words
 * @return String
 */
 
function splitLongWords(str, max, truncationChar) {
  str = str.trim()
  var result = []
  var words = str.split(' ')
  var remainder = ''
 
  var truncationWidth = wcwidth(truncationChar)
 
  while (remainder || words.length) {
    if (remainder) {
      var word = remainder
      remainder = ''
    } else {
      var word = words.shift()
    }
 
    if (wcwidth(word) > max) {
      // slice is based on length no wcwidth
      var i = 0
      var wwidth = 0
      var limit = max - truncationWidth
      while (i < word.length) {
        var w = wcwidth(word.charAt(i))
        if (w + wwidth > limit) {
          break
        }
        wwidth += w
        ++i
      }
 
      remainder = word.slice(i) // get remainder
      // save remainder for next loop
 
      word = word.slice(0, i) // grab truncated word
      word += truncationChar // add trailing … or whatever
    }
    result.push(word)
  }
 
  return result.join(' ')
}
 
 
/**
 * Truncate `str` into total width `max`
 * If `str` is shorter than `max`,  will return `str` unaltered.
 *
 * @param String str string to truncated
 * @param Number max total wcwidth of output string
 * @return String truncated str
 */
 
function truncateString(str, max) {
 
  str = str != null ? str : ''
  str = String(str)
 
  if(max == Infinity) return str
 
  var i = 0
  var wwidth = 0
  while (i < str.length) {
    var w = wcwidth(str.charAt(i))
    if(w + wwidth > max)
      break
    wwidth += w
    ++i
  }
  return str.slice(0, i)
}
 
 
 
/**
 * Exports
 */
 
module.exports.padRight = padRight
module.exports.padCenter = padCenter
module.exports.padLeft = padLeft
module.exports.splitIntoLines = splitIntoLines
module.exports.splitLongWords = splitLongWords
module.exports.truncateString = truncateString
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/width.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/width.js

Statements: 75% (3 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 75% (3 / 4)      Ignored: none     

1 2 3 4 5 6 7 81 1   1        
var stripAnsi = require('strip-ansi')
var wcwidth = require('wcwidth')
 
module.exports = function(str) {
  return wcwidth(stripAnsi(str))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/

Statements: 21.43% (9 / 42)      Branches: 0% (0 / 46)      Functions: 0% (0 / 6)      Lines: 26.47% (9 / 34)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/
File Statements Branches Functions Lines
combining.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
index.js 19.51% (8 / 41) 0% (0 / 46) 0% (0 / 6) 24.24% (8 / 33)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/combining.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/combining.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521                                                                                                      
module.exports = [
    [ 0x0300, 0x036F ], [ 0x0483, 0x0486 ], [ 0x0488, 0x0489 ],
    [ 0x0591, 0x05BD ], [ 0x05BF, 0x05BF ], [ 0x05C1, 0x05C2 ],
    [ 0x05C4, 0x05C5 ], [ 0x05C7, 0x05C7 ], [ 0x0600, 0x0603 ],
    [ 0x0610, 0x0615 ], [ 0x064B, 0x065E ], [ 0x0670, 0x0670 ],
    [ 0x06D6, 0x06E4 ], [ 0x06E7, 0x06E8 ], [ 0x06EA, 0x06ED ],
    [ 0x070F, 0x070F ], [ 0x0711, 0x0711 ], [ 0x0730, 0x074A ],
    [ 0x07A6, 0x07B0 ], [ 0x07EB, 0x07F3 ], [ 0x0901, 0x0902 ],
    [ 0x093C, 0x093C ], [ 0x0941, 0x0948 ], [ 0x094D, 0x094D ],
    [ 0x0951, 0x0954 ], [ 0x0962, 0x0963 ], [ 0x0981, 0x0981 ],
    [ 0x09BC, 0x09BC ], [ 0x09C1, 0x09C4 ], [ 0x09CD, 0x09CD ],
    [ 0x09E2, 0x09E3 ], [ 0x0A01, 0x0A02 ], [ 0x0A3C, 0x0A3C ],
    [ 0x0A41, 0x0A42 ], [ 0x0A47, 0x0A48 ], [ 0x0A4B, 0x0A4D ],
    [ 0x0A70, 0x0A71 ], [ 0x0A81, 0x0A82 ], [ 0x0ABC, 0x0ABC ],
    [ 0x0AC1, 0x0AC5 ], [ 0x0AC7, 0x0AC8 ], [ 0x0ACD, 0x0ACD ],
    [ 0x0AE2, 0x0AE3 ], [ 0x0B01, 0x0B01 ], [ 0x0B3C, 0x0B3C ],
    [ 0x0B3F, 0x0B3F ], [ 0x0B41, 0x0B43 ], [ 0x0B4D, 0x0B4D ],
    [ 0x0B56, 0x0B56 ], [ 0x0B82, 0x0B82 ], [ 0x0BC0, 0x0BC0 ],
    [ 0x0BCD, 0x0BCD ], [ 0x0C3E, 0x0C40 ], [ 0x0C46, 0x0C48 ],
    [ 0x0C4A, 0x0C4D ], [ 0x0C55, 0x0C56 ], [ 0x0CBC, 0x0CBC ],
    [ 0x0CBF, 0x0CBF ], [ 0x0CC6, 0x0CC6 ], [ 0x0CCC, 0x0CCD ],
    [ 0x0CE2, 0x0CE3 ], [ 0x0D41, 0x0D43 ], [ 0x0D4D, 0x0D4D ],
    [ 0x0DCA, 0x0DCA ], [ 0x0DD2, 0x0DD4 ], [ 0x0DD6, 0x0DD6 ],
    [ 0x0E31, 0x0E31 ], [ 0x0E34, 0x0E3A ], [ 0x0E47, 0x0E4E ],
    [ 0x0EB1, 0x0EB1 ], [ 0x0EB4, 0x0EB9 ], [ 0x0EBB, 0x0EBC ],
    [ 0x0EC8, 0x0ECD ], [ 0x0F18, 0x0F19 ], [ 0x0F35, 0x0F35 ],
    [ 0x0F37, 0x0F37 ], [ 0x0F39, 0x0F39 ], [ 0x0F71, 0x0F7E ],
    [ 0x0F80, 0x0F84 ], [ 0x0F86, 0x0F87 ], [ 0x0F90, 0x0F97 ],
    [ 0x0F99, 0x0FBC ], [ 0x0FC6, 0x0FC6 ], [ 0x102D, 0x1030 ],
    [ 0x1032, 0x1032 ], [ 0x1036, 0x1037 ], [ 0x1039, 0x1039 ],
    [ 0x1058, 0x1059 ], [ 0x1160, 0x11FF ], [ 0x135F, 0x135F ],
    [ 0x1712, 0x1714 ], [ 0x1732, 0x1734 ], [ 0x1752, 0x1753 ],
    [ 0x1772, 0x1773 ], [ 0x17B4, 0x17B5 ], [ 0x17B7, 0x17BD ],
    [ 0x17C6, 0x17C6 ], [ 0x17C9, 0x17D3 ], [ 0x17DD, 0x17DD ],
    [ 0x180B, 0x180D ], [ 0x18A9, 0x18A9 ], [ 0x1920, 0x1922 ],
    [ 0x1927, 0x1928 ], [ 0x1932, 0x1932 ], [ 0x1939, 0x193B ],
    [ 0x1A17, 0x1A18 ], [ 0x1B00, 0x1B03 ], [ 0x1B34, 0x1B34 ],
    [ 0x1B36, 0x1B3A ], [ 0x1B3C, 0x1B3C ], [ 0x1B42, 0x1B42 ],
    [ 0x1B6B, 0x1B73 ], [ 0x1DC0, 0x1DCA ], [ 0x1DFE, 0x1DFF ],
    [ 0x200B, 0x200F ], [ 0x202A, 0x202E ], [ 0x2060, 0x2063 ],
    [ 0x206A, 0x206F ], [ 0x20D0, 0x20EF ], [ 0x302A, 0x302F ],
    [ 0x3099, 0x309A ], [ 0xA806, 0xA806 ], [ 0xA80B, 0xA80B ],
    [ 0xA825, 0xA826 ], [ 0xFB1E, 0xFB1E ], [ 0xFE00, 0xFE0F ],
    [ 0xFE20, 0xFE23 ], [ 0xFEFF, 0xFEFF ], [ 0xFFF9, 0xFFFB ],
    [ 0x10A01, 0x10A03 ], [ 0x10A05, 0x10A06 ], [ 0x10A0C, 0x10A0F ],
    [ 0x10A38, 0x10A3A ], [ 0x10A3F, 0x10A3F ], [ 0x1D167, 0x1D169 ],
    [ 0x1D173, 0x1D182 ], [ 0x1D185, 0x1D18B ], [ 0x1D1AA, 0x1D1AD ],
    [ 0x1D242, 0x1D244 ], [ 0xE0001, 0xE0001 ], [ 0xE0020, 0xE007F ],
    [ 0xE0100, 0xE01EF ]
]
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/index.js

Statements: 19.51% (8 / 41)      Branches: 0% (0 / 46)      Functions: 0% (0 / 6)      Lines: 24.24% (8 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101    1 1   1         1       1                                                             1                         1                                                 1                                  
"use strict"
 
var defaults = require('defaults')
var combining = require('./combining')
 
var DEFAULTS = {
  nul: 0,
  control: 0
}
 
module.exports = function wcwidth(str) {
  return wcswidth(str, DEFAULTS)
}
 
module.exports.config = function(opts) {
  opts = defaults(opts || {}, DEFAULTS)
  return function wcwidth(str) {
    return wcswidth(str, opts)
  }
}
 
/*
 *  The following functions define the column width of an ISO 10646
 *  character as follows:
 *  - The null character (U+0000) has a column width of 0.
 *  - Other C0/C1 control characters and DEL will lead to a return value
 *    of -1.
 *  - Non-spacing and enclosing combining characters (general category
 *    code Mn or Me in the
 *    Unicode database) have a column width of 0.
 *  - SOFT HYPHEN (U+00AD) has a column width of 1.
 *  - Other format characters (general category code Cf in the Unicode
 *    database) and ZERO WIDTH
 *    SPACE (U+200B) have a column width of 0.
 *  - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
 *    have a column width of 0.
 *  - Spacing characters in the East Asian Wide (W) or East Asian
 *    Full-width (F) category as
 *    defined in Unicode Technical Report #11 have a column width of 2.
 *  - All remaining characters (including all printable ISO 8859-1 and
 *    WGL4 characters, Unicode control characters, etc.) have a column
 *    width of 1.
 *  This implementation assumes that characters are encoded in ISO 10646.
*/
 
function wcswidth(str, opts) {
  if (typeof str !== 'string') return wcwidth(str, opts)
 
  var s = 0
  for (var i = 0; i < str.length; i++) {
    var n = wcwidth(str.charCodeAt(i), opts)
    if (n < 0) return -1
    s += n
  }
 
  return s
}
 
function wcwidth(ucs, opts) {
  // test for 8-bit control characters
  if (ucs === 0) return opts.nul
  if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return opts.control
 
  // binary search in table of non-spacing characters
  if (bisearch(ucs)) return 0
 
  // if we arrive here, ucs is not a combining or C0/C1 control character
  return 1 +
      (ucs >= 0x1100 &&
       (ucs <= 0x115f ||                       // Hangul Jamo init. consonants
        ucs == 0x2329 || ucs == 0x232a ||
        (ucs >= 0x2e80 && ucs <= 0xa4cf &&
         ucs != 0x303f) ||                     // CJK ... Yi
        (ucs >= 0xac00 && ucs <= 0xd7a3) ||    // Hangul Syllables
        (ucs >= 0xf900 && ucs <= 0xfaff) ||    // CJK Compatibility Ideographs
        (ucs >= 0xfe10 && ucs <= 0xfe19) ||    // Vertical forms
        (ucs >= 0xfe30 && ucs <= 0xfe6f) ||    // CJK Compatibility Forms
        (ucs >= 0xff00 && ucs <= 0xff60) ||    // Fullwidth Forms
        (ucs >= 0xffe0 && ucs <= 0xffe6) ||
        (ucs >= 0x20000 && ucs <= 0x2fffd) ||
        (ucs >= 0x30000 && ucs <= 0x3fffd)));
}
 
function bisearch(ucs) {
  var min = 0
  var max = combining.length - 1
  var mid
 
  if (ucs < combining[0][0] || ucs > combining[max][1]) return false
 
  while (max >= min) {
    mid = Math.floor((min + max) / 2)
    if (ucs > combining[mid][1]) min = mid + 1
    else if (ucs < combining[mid][0]) max = mid - 1
    else return true
  }
 
  return false
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/
File Statements Branches Functions Lines
index.js 28.57% (2 / 7) 0% (0 / 4) 0% (0 / 2) 28.57% (2 / 7)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/index.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 141   1                      
var clone = require('clone');
 
module.exports = function(options, defaults) {
  options = options || {};
 
  Object.keys(defaults).forEach(function(key) {
    if (typeof options[key] === 'undefined') {
      options[key] = clone(defaults[key]);
    }
  });
 
  return options;
};
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/node_modules/clone/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/node_modules/clone/

Statements: 19.54% (17 / 87)      Branches: 5.56% (3 / 54)      Functions: 10% (1 / 10)      Lines: 20.48% (17 / 83)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/node_modules/clone/
File Statements Branches Functions Lines
clone.js 19.54% (17 / 87) 5.56% (3 / 54) 10% (1 / 10) 20.48% (17 / 83)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/node_modules/clone/clone.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/columnify/node_modules/wcwidth/node_modules/defaults/node_modules/clone/clone.js

Statements: 19.54% (17 / 87)      Branches: 5.56% (3 / 54)      Functions: 10% (1 / 10)      Lines: 20.48% (17 / 83)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 1621                                         1                                           1                                                                                                                                             1                     1     1   1     1   1     1   1     1   1             1   1     1 1      
var clone = (function() {
'use strict';
 
/**
 * Clones (copies) an Object using deep copying.
 *
 * This function supports circular references by default, but if you are certain
 * there are no circular references in your object, you can save some CPU time
 * by calling clone(obj, false).
 *
 * Caution: if `circular` is false and `parent` contains circular references,
 * your program may enter an infinite loop and crash.
 *
 * @param `parent` - the object to be cloned
 * @param `circular` - set to true if the object to be cloned may contain
 *    circular references. (optional - true by default)
 * @param `depth` - set to a number if the object is only to be cloned to
 *    a particular depth. (optional - defaults to Infinity)
 * @param `prototype` - sets the prototype to be used when cloning an object.
 *    (optional - defaults to parent prototype).
*/
function clone(parent, circular, depth, prototype) {
  var filter;
  if (typeof circular === 'object') {
    depth = circular.depth;
    prototype = circular.prototype;
    filter = circular.filter;
    circular = circular.circular
  }
  // maintain two arrays for circular references, where corresponding parents
  // and children have the same index
  var allParents = [];
  var allChildren = [];
 
  var useBuffer = typeof Buffer != 'undefined';
 
  if (typeof circular == 'undefined')
    circular = true;
 
  if (typeof depth == 'undefined')
    depth = Infinity;
 
  // recurse this function so we don't reset allParents and allChildren
  function _clone(parent, depth) {
    // cloning null always returns null
    if (parent === null)
      return null;
 
    if (depth == 0)
      return parent;
 
    var child;
    var proto;
    if (typeof parent != 'object') {
      return parent;
    }
 
    if (clone.__isArray(parent)) {
      child = [];
    } else if (clone.__isRegExp(parent)) {
      child = new RegExp(parent.source, __getRegExpFlags(parent));
      if (parent.lastIndex) child.lastIndex = parent.lastIndex;
    } else if (clone.__isDate(parent)) {
      child = new Date(parent.getTime());
    } else if (useBuffer && Buffer.isBuffer(parent)) {
      child = new Buffer(parent.length);
      parent.copy(child);
      return child;
    } else {
      if (typeof prototype == 'undefined') {
        proto = Object.getPrototypeOf(parent);
        child = Object.create(proto);
      }
      else {
        child = Object.create(prototype);
        proto = prototype;
      }
    }
 
    if (circular) {
      var index = allParents.indexOf(parent);
 
      if (index != -1) {
        return allChildren[index];
      }
      allParents.push(parent);
      allChildren.push(child);
    }
 
    for (var i in parent) {
      var attrs;
      if (proto) {
        attrs = Object.getOwnPropertyDescriptor(proto, i);
      }
 
      if (attrs && attrs.set == null) {
        continue;
      }
      child[i] = _clone(parent[i], depth - 1);
    }
 
    return child;
  }
 
  return _clone(parent, depth);
}
 
/**
 * Simple flat clone using prototype, accepts only objects, usefull for property
 * override on FLAT configuration object (no nested props).
 *
 * USE WITH CAUTION! This may not behave as you wish if you do not know how this
 * works.
 */
clone.clonePrototype = function clonePrototype(parent) {
  if (parent === null)
    return null;
 
  var c = function () {};
  c.prototype = parent;
  return new c();
};
 
// private utility functions
 
function __objToStr(o) {
  return Object.prototype.toString.call(o);
};
clone.__objToStr = __objToStr;
 
function __isDate(o) {
  return typeof o === 'object' && __objToStr(o) === '[object Date]';
};
clone.__isDate = __isDate;
 
function __isArray(o) {
  return typeof o === 'object' && __objToStr(o) === '[object Array]';
};
clone.__isArray = __isArray;
 
function __isRegExp(o) {
  return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
};
clone.__isRegExp = __isRegExp;
 
function __getRegExpFlags(re) {
  var flags = '';
  if (re.global) flags += 'g';
  if (re.ignoreCase) flags += 'i';
  if (re.multiline) flags += 'm';
  return flags;
};
clone.__getRegExpFlags = __getRegExpFlags;
 
return clone;
})();
 
Eif (typeof module === 'object' && module.exports) {
  module.exports = clone;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/

Statements: 14.04% (25 / 178)      Branches: 0% (0 / 95)      Functions: 4% (1 / 25)      Lines: 14.97% (25 / 167)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/config-chain/
File Statements Branches Functions Lines
index.js 14.04% (25 / 178) 0% (0 / 95) 4% (1 / 25) 14.97% (25 / 167)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/index.js

Statements: 14.04% (25 / 178)      Branches: 0% (0 / 95)      Functions: 4% (1 / 25)      Lines: 14.97% (25 / 167)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 2841               1                                 1     1                         1                                     1                       1                       1 1                 1     1 16   1   1                                   1                                     1                   1                                                                               1                         1             1                                                               1           1                                                 1   1       1          
var ProtoList = require('proto-list')
  , path = require('path')
  , fs = require('fs')
  , ini = require('ini')
  , EE = require('events').EventEmitter
  , url = require('url')
  , http = require('http')
 
var exports = module.exports = function () {
  var args = [].slice.call(arguments)
    , conf = new ConfigChain()
 
  while(args.length) {
    var a = args.shift()
    if(a) conf.push
          ( 'string' === typeof a
            ? json(a)
            : a )
  }
 
  return conf
}
 
//recursively find a file...
 
var find = exports.find = function () {
  var rel = path.join.apply(null, [].slice.call(arguments))
 
  function find(start, rel) {
    var file = path.join(start, rel)
    try {
      fs.statSync(file)
      return file
    } catch (err) {
      if(path.dirname(start) !== start) // root
        return find(path.dirname(start), rel)
    }
  }
  return find(__dirname, rel)
}
 
var parse = exports.parse = function (content, file, type) {
  content = '' + content
  // if we don't know what it is, try json and fall back to ini
  // if we know what it is, then it must be that.
  if (!type) {
    try { return JSON.parse(content) }
    catch (er) { return ini.parse(content) }
  } else if (type === 'json') {
    if (this.emit) {
      try { return JSON.parse(content) }
      catch (er) { this.emit('error', er) }
    } else {
      return JSON.parse(content)
    }
  } else {
    return ini.parse(content)
  }
}
 
var json = exports.json = function () {
  var args = [].slice.call(arguments).filter(function (arg) { return arg != null })
  var file = path.join.apply(null, args)
  var content
  try {
    content = fs.readFileSync(file,'utf-8')
  } catch (err) {
    return
  }
  return parse(content, file, 'json')
}
 
var env = exports.env = function (prefix, env) {
  env = env || process.env
  var obj = {}
  var l = prefix.length
  for(var k in env) {
    if(k.indexOf(prefix) === 0)
      obj[k.substring(l)] = env[k]
  }
 
  return obj
}
 
exports.ConfigChain = ConfigChain
function ConfigChain () {
  EE.apply(this)
  ProtoList.apply(this, arguments)
  this._awaiting = 0
  this._saving = 0
  this.sources = {}
}
 
// multi-inheritance-ish
var extras = {
  constructor: { value: ConfigChain }
}
Object.keys(EE.prototype).forEach(function (k) {
  extras[k] = Object.getOwnPropertyDescriptor(EE.prototype, k)
})
ConfigChain.prototype = Object.create(ProtoList.prototype, extras)
 
ConfigChain.prototype.del = function (key, where) {
  // if not specified where, then delete from the whole chain, scorched
  // earth style
  if (where) {
    var target = this.sources[where]
    target = target && target.data
    if (!target) {
      return this.emit('error', new Error('not found '+where))
    }
    delete target[key]
  } else {
    for (var i = 0, l = this.list.length; i < l; i ++) {
      delete this.list[i][key]
    }
  }
  return this
}
 
ConfigChain.prototype.set = function (key, value, where) {
  var target
 
  if (where) {
    target = this.sources[where]
    target = target && target.data
    if (!target) {
      return this.emit('error', new Error('not found '+where))
    }
  } else {
    target = this.list[0]
    if (!target) {
      return this.emit('error', new Error('cannot set, no confs!'))
    }
  }
  target[key] = value
  return this
}
 
ConfigChain.prototype.get = function (key, where) {
  if (where) {
    where = this.sources[where]
    if (where) where = where.data
    if (where && Object.hasOwnProperty.call(where, key)) return where[key]
    return undefined
  }
  return this.list[0][key]
}
 
ConfigChain.prototype.save = function (where, type, cb) {
  if (typeof type === 'function') cb = type, type = null
  var target = this.sources[where]
  if (!target || !(target.path || target.source) || !target.data) {
    // TODO: maybe save() to a url target could be a PUT or something?
    // would be easy to swap out with a reddis type thing, too
    return this.emit('error', new Error('bad save target: '+where))
  }
 
  if (target.source) {
    var pref = target.prefix || ''
    Object.keys(target.data).forEach(function (k) {
      target.source[pref + k] = target.data[k]
    })
    return this
  }
 
  var type = type || target.type
  var data = target.data
  if (target.type === 'json') {
    data = JSON.stringify(data)
  } else {
    data = ini.stringify(data)
  }
 
  this._saving ++
  fs.writeFile(target.path, data, 'utf8', function (er) {
    this._saving --
    if (er) {
      if (cb) return cb(er)
      else return this.emit('error', er)
    }
    if (this._saving === 0) {
      if (cb) cb()
      this.emit('save')
    }
  }.bind(this))
  return this
}
 
ConfigChain.prototype.addFile = function (file, type, name) {
  name = name || file
  var marker = {__source__:name}
  this.sources[name] = { path: file, type: type }
  this.push(marker)
  this._await()
  fs.readFile(file, 'utf8', function (er, data) {
    if (er) this.emit('error', er)
    this.addString(data, file, type, marker)
  }.bind(this))
  return this
}
 
ConfigChain.prototype.addEnv = function (prefix, env, name) {
  name = name || 'env'
  var data = exports.env(prefix, env)
  this.sources[name] = { data: data, source: env, prefix: prefix }
  return this.add(data, name)
}
 
ConfigChain.prototype.addUrl = function (req, type, name) {
  this._await()
  var href = url.format(req)
  name = name || href
  var marker = {__source__:name}
  this.sources[name] = { href: href, type: type }
  this.push(marker)
  http.request(req, function (res) {
    var c = []
    var ct = res.headers['content-type']
    if (!type) {
      type = ct.indexOf('json') !== -1 ? 'json'
           : ct.indexOf('ini') !== -1 ? 'ini'
           : href.match(/\.json$/) ? 'json'
           : href.match(/\.ini$/) ? 'ini'
           : null
      marker.type = type
    }
 
    res.on('data', c.push.bind(c))
    .on('end', function () {
      this.addString(Buffer.concat(c), href, type, marker)
    }.bind(this))
    .on('error', this.emit.bind(this, 'error'))
 
  }.bind(this))
  .on('error', this.emit.bind(this, 'error'))
  .end()
 
  return this
}
 
ConfigChain.prototype.addString = function (data, file, type, marker) {
  data = this.parse(data, file, type)
  this.add(data, marker)
  return this
}
 
ConfigChain.prototype.add = function (data, marker) {
  if (marker && typeof marker === 'object') {
    var i = this.list.indexOf(marker)
    if (i === -1) {
      return this.emit('error', new Error('bad marker'))
    }
    this.splice(i, 1, data)
    marker = marker.__source__
    this.sources[marker] = this.sources[marker] || {}
    this.sources[marker].data = data
    // we were waiting for this.  maybe emit 'load'
    this._resolve()
  } else {
    if (typeof marker === 'string') {
      this.sources[marker] = this.sources[marker] || {}
      this.sources[marker].data = data
    }
    // trigger the load event if nothing was already going to do so.
    this._await()
    this.push(data)
    process.nextTick(this._resolve.bind(this))
  }
  return this
}
 
ConfigChain.prototype.parse = exports.parse
 
ConfigChain.prototype._await = function () {
  this._awaiting++
}
 
ConfigChain.prototype._resolve = function () {
  this._awaiting--
  if (this._awaiting === 0) this.emit('load', this)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/node_modules/proto-list/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/node_modules/proto-list/

Statements: 7.84% (4 / 51)      Branches: 0% (0 / 22)      Functions: 0% (0 / 18)      Lines: 8.89% (4 / 45)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/config-chain/node_modules/proto-list/
File Statements Branches Functions Lines
proto-list.js 7.84% (4 / 51) 0% (0 / 22) 0% (0 / 18) 8.89% (4 / 45)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/node_modules/proto-list/proto-list.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/config-chain/node_modules/proto-list/proto-list.js

Statements: 7.84% (4 / 51)      Branches: 0% (0 / 22)      Functions: 0% (0 / 18)      Lines: 8.89% (4 / 45)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90  1   1             1                               1                                                                                                                              
 
module.exports = ProtoList
 
function setProto(obj, proto) {
  if (typeof Object.setPrototypeOf === "function")
    return Object.setPrototypeOf(obj, proto)
  else
    obj.__proto__ = proto
}
 
function ProtoList () {
  this.list = []
  var root = null
  Object.defineProperty(this, 'root', {
    get: function () { return root },
    set: function (r) {
      root = r
      if (this.list.length) {
        setProto(this.list[this.list.length - 1], r)
      }
    },
    enumerable: true,
    configurable: true
  })
}
 
ProtoList.prototype =
  { get length () { return this.list.length }
  , get keys () {
      var k = []
      for (var i in this.list[0]) k.push(i)
      return k
    }
  , get snapshot () {
      var o = {}
      this.keys.forEach(function (k) { o[k] = this.get(k) }, this)
      return o
    }
  , get store () {
      return this.list[0]
    }
  , push : function (obj) {
      if (typeof obj !== "object") obj = {valueOf:obj}
      if (this.list.length >= 1) {
        setProto(this.list[this.list.length - 1], obj)
      }
      setProto(obj, this.root)
      return this.list.push(obj)
    }
  , pop : function () {
      if (this.list.length >= 2) {
        setProto(this.list[this.list.length - 2], this.root)
      }
      return this.list.pop()
    }
  , unshift : function (obj) {
      setProto(obj, this.list[0] || this.root)
      return this.list.unshift(obj)
    }
  , shift : function () {
      if (this.list.length === 1) {
        setProto(this.list[0], this.root)
      }
      return this.list.shift()
    }
  , get : function (key) {
      return this.list[0][key]
    }
  , set : function (key, val, save) {
      if (!this.length) this.push({})
      if (save && this.list[0].hasOwnProperty(key)) this.push({})
      return this.list[0][key] = val
    }
  , forEach : function (fn, thisp) {
      for (var key in this.list[0]) fn.call(thisp, key, this.list[0][key])
    }
  , slice : function () {
      return this.list.slice.apply(this.list, arguments)
    }
  , splice : function () {
      // handle injections
      var ret = this.list.splice.apply(this.list, arguments)
      for (var i = 0, l = this.list.length; i < l; i++) {
        setProto(this.list[i], this.list[i + 1] || this.root)
      }
      return ret
    }
  }
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/debuglog/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/debuglog/

Statements: 35.71% (5 / 14)      Branches: 44.44% (4 / 9)      Functions: 0% (0 / 3)      Lines: 35.71% (5 / 14)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/debuglog/
File Statements Branches Functions Lines
debuglog.js 35.71% (5 / 14) 44.44% (4 / 9) 0% (0 / 3) 35.71% (5 / 14)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/debuglog/debuglog.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/debuglog/debuglog.js

Statements: 35.71% (5 / 14)      Branches: 44.44% (4 / 9)      Functions: 0% (0 / 3)      Lines: 35.71% (5 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 241   1   1 1   1                                
var util = require('util');
 
module.exports = (util && util.debuglog) || debuglog;
 
var debugs = {};
var debugEnviron = process.env.NODE_DEBUG || '';
 
function debuglog(set) {
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = util.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/dezalgo/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/dezalgo/

Statements: 28.57% (4 / 14)      Branches: 0% (0 / 2)      Functions: 0% (0 / 4)      Lines: 28.57% (4 / 14)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/dezalgo/
File Statements Branches Functions Lines
dezalgo.js 28.57% (4 / 14) 0% (0 / 2) 0% (0 / 4) 28.57% (4 / 14)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/dezalgo/dezalgo.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/dezalgo/dezalgo.js

Statements: 28.57% (4 / 14)      Branches: 0% (0 / 2)      Functions: 0% (0 / 4)      Lines: 28.57% (4 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 241 1   1   1                                    
var wrappy = require('wrappy')
module.exports = wrappy(dezalgo)
 
var asap = require('asap')
 
function dezalgo (cb) {
  var sync = true
  asap(function () {
    sync = false
  })
 
  return function zalgoSafe() {
    var args = arguments
    var me = this
    if (sync)
      asap(function() {
        cb.apply(me, args)
      })
    else
      cb.apply(me, args)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/editor/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/editor/

Statements: 13.33% (2 / 15)      Branches: 0% (0 / 12)      Functions: 0% (0 / 2)      Lines: 15.38% (2 / 13)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/editor/
File Statements Branches Functions Lines
index.js 13.33% (2 / 15) 0% (0 / 12) 0% (0 / 2) 15.38% (2 / 13)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/editor/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/editor/index.js

Statements: 13.33% (2 / 15)      Branches: 0% (0 / 12)      Functions: 0% (0 / 2)      Lines: 15.38% (2 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 221   1                                      
var spawn = require('child_process').spawn;
 
module.exports = function (file, opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    
    var ed = /^win/.test(process.platform) ? 'notepad' : 'vim';
    var editor = opts.editor || process.env.VISUAL || process.env.EDITOR || ed;
    var args = editor.split(/\s+/);
    var bin = args.shift();
    
    var ps = spawn(bin, args.concat([ file ]), { stdio: 'inherit' });
    
    ps.on('exit', function (code, sig) {
        if (typeof cb === 'function') cb(code, sig)
    });
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-vacuum/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-vacuum/

Statements: 15.19% (12 / 79)      Branches: 0% (0 / 59)      Functions: 0% (0 / 9)      Lines: 16.44% (12 / 73)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fs-vacuum/
File Statements Branches Functions Lines
vacuum.js 15.19% (12 / 79) 0% (0 / 59) 0% (0 / 9) 16.44% (12 / 73)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-vacuum/vacuum.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-vacuum/vacuum.js

Statements: 15.19% (12 / 79)      Branches: 0% (0 / 59)      Functions: 0% (0 / 9)      Lines: 16.44% (12 / 73)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 1191 1 1 1   1 1 1 1 1   1   1                                                                                             1                                                                                                                    
var assert = require('assert')
var dirname = require('path').dirname
var resolve = require('path').resolve
var isInside = require('path-is-inside')
 
var rimraf = require('rimraf')
var lstat = require('graceful-fs').lstat
var readdir = require('graceful-fs').readdir
var rmdir = require('graceful-fs').rmdir
var unlink = require('graceful-fs').unlink
 
module.exports = vacuum
 
function vacuum (leaf, options, cb) {
  assert(typeof leaf === 'string', 'must pass in path to remove')
  assert(typeof cb === 'function', 'must pass in callback')
 
  if (!options) options = {}
  assert(typeof options === 'object', 'options must be an object')
 
  var log = options.log ? options.log : function () {}
 
  leaf = leaf && resolve(leaf)
  var base = options.base && resolve(options.base)
  if (base && !isInside(leaf, base)) {
    return cb(new Error(leaf + ' is not a child of ' + base))
  }
 
  lstat(leaf, function (error, stat) {
    if (error) {
      if (error.code === 'ENOENT') return cb(null)
 
      log(error.stack)
      return cb(error)
    }
 
    if (!(stat && (stat.isDirectory() || stat.isSymbolicLink() || stat.isFile()))) {
      log(leaf, 'is not a directory, file, or link')
      return cb(new Error(leaf + ' is not a directory, file, or link'))
    }
 
    if (options.purge) {
      log('purging', leaf)
      rimraf(leaf, function (error) {
        if (error) return cb(error)
 
        next(dirname(leaf))
      })
    } else if (!stat.isDirectory()) {
      log('removing', leaf)
      unlink(leaf, function (error) {
        if (error) return cb(error)
 
        next(dirname(leaf))
      })
    } else {
      next(leaf)
    }
  })
 
  function next (branch) {
    branch = branch && resolve(branch)
    // either we've reached the base or we've reached the root
    if ((base && branch === base) || branch === dirname(branch)) {
      log('finished vacuuming up to', branch)
      return cb(null)
    }
 
    readdir(branch, function (error, files) {
      if (error) {
        if (error.code === 'ENOENT') return cb(null)
 
        log('unable to check directory', branch, 'due to', error.message)
        return cb(error)
      }
 
      if (files.length > 0) {
        log('quitting because other entries in', branch)
        return cb(null)
      }
 
      if (branch === process.env.HOME) {
        log('quitting because cannot remove home directory', branch)
        return cb(null)
      }
 
      log('removing', branch)
      lstat(branch, function (error, stat) {
        if (error) {
          if (error.code === 'ENOENT') return cb(null)
 
          log('unable to lstat', branch, 'due to', error.message)
          return cb(error)
        }
 
        var remove = stat.isDirectory() ? rmdir : unlink
        remove(branch, function (error) {
          if (error) {
            if (error.code === 'ENOENT') {
              log('quitting because lost the race to remove', branch)
              return cb(null)
            }
            if (error.code === 'ENOTEMPTY' || error.code === 'EEXIST') {
              log('quitting because new (racy) entries in', branch)
              return cb(null)
            }
 
            log('unable to remove', branch, 'due to', error.message)
            return cb(error)
          }
 
          next(dirname(branch))
        })
      })
    })
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-write-stream-atomic/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-write-stream-atomic/

Statements: 26.26% (26 / 99)      Branches: 2.86% (1 / 35)      Functions: 0% (0 / 23)      Lines: 27.96% (26 / 93)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fs-write-stream-atomic/
File Statements Branches Functions Lines
index.js 26.26% (26 / 99) 2.86% (1 / 35) 0% (0 / 23) 27.96% (26 / 93)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-write-stream-atomic/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fs-write-stream-atomic/index.js

Statements: 26.26% (26 / 99)      Branches: 2.86% (1 / 35)      Functions: 0% (0 / 23)      Lines: 27.96% (26 / 93)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 1781 1 1 1 1 1   1               1 1       1   1                   1 1                                                     1         1           1           1                         1       1                     1                           1           1                     1                     1                           1             1                  
var fs = require('graceful-fs')
var Writable = require('readable-stream').Writable
var util = require('util')
var MurmurHash3 = require('imurmurhash')
var iferr = require('iferr')
var crypto = require('crypto')
 
function murmurhex () {
  var hash = MurmurHash3('')
  for (var ii = 0; ii < arguments.length; ++ii) {
    hash.hash('' + arguments[ii])
  }
  return hash.result()
}
 
var invocations = 0
function getTmpname (filename) {
  return filename + '.' + murmurhex(__filename, process.pid, ++invocations)
}
 
var setImmediate = global.setImmediate || setTimeout
 
module.exports = WriteStreamAtomic
 
// Requirements:
//   1. Write everything written to the stream to a temp file.
//   2. If there are no errors:
//      a. moves the temp file into its final destination
//      b. emits `finish` & `closed` ONLY after the file is
//         fully flushed and renamed.
//   3. If there's an error, removes the temp file.
 
util.inherits(WriteStreamAtomic, Writable)
function WriteStreamAtomic (path, options) {
  if (!(this instanceof WriteStreamAtomic)) {
    return new WriteStreamAtomic(path, options)
  }
  Writable.call(this, options)
 
  this.__isWin = options && options.hasOwnProperty('isWin') ? options.isWin : process.platform === 'win32'
 
  this.__atomicTarget = path
  this.__atomicTmp = getTmpname(path)
 
  this.__atomicChown = options && options.chown
 
  this.__atomicClosed = false
 
  this.__atomicStream = fs.WriteStream(this.__atomicTmp, options)
 
  this.__atomicStream.once('open', handleOpen(this))
  this.__atomicStream.once('close', handleClose(this))
  this.__atomicStream.once('error', handleError(this))
}
 
// We have to suppress default finish emitting, because ordinarily it
// would happen as soon as `end` is called on us and all of the
// data has been written to our target stream. So we suppress
// finish from being emitted here, and only emit it after our
// target stream is closed and we've moved everything around.
WriteStreamAtomic.prototype.emit = function (event) {
  if (event === 'finish') return this.__atomicStream.end()
  return Writable.prototype.emit.apply(this, arguments)
}
 
WriteStreamAtomic.prototype._write = function (buffer, encoding, cb) {
  var flushed = this.__atomicStream.write(buffer, encoding)
  if (flushed) return cb()
  this.__atomicStream.once('drain', cb)
}
 
function handleOpen (writeStream) {
  return function (fd) {
    writeStream.emit('open', fd)
  }
}
 
function handleClose (writeStream) {
  return function () {
    if (writeStream.__atomicClosed) return
    writeStream.__atomicClosed = true
    if (writeStream.__atomicChown) {
      var uid = writeStream.__atomicChown.uid
      var gid = writeStream.__atomicChown.gid
      return fs.chown(writeStream.__atomicTmp, uid, gid, iferr(cleanup, moveIntoPlace))
    } else {
      moveIntoPlace()
    }
  }
 
  function moveIntoPlace () {
    fs.rename(writeStream.__atomicTmp, writeStream.__atomicTarget, iferr(trapWindowsEPERM, end))
  }
 
  function trapWindowsEPERM (err) {
    if (writeStream.__isWin &&
        err.syscall && err.syscall === 'rename' &&
        err.code && err.code === 'EPERM'
    ) {
      checkFileHashes(err)
    } else {
      cleanup(err)
    }
  }
 
  function checkFileHashes (eperm) {
    var inprocess = 2
    var tmpFileHash = crypto.createHash('sha512')
    var targetFileHash = crypto.createHash('sha512')
 
    fs.createReadStream(writeStream.__atomicTmp)
      .on('data', function (data, enc) { tmpFileHash.update(data, enc) })
      .on('error', fileHashError)
      .on('end', fileHashComplete)
    fs.createReadStream(writeStream.__atomicTarget)
      .on('data', function (data, enc) { targetFileHash.update(data, enc) })
      .on('error', fileHashError)
      .on('end', fileHashComplete)
 
    function fileHashError () {
      if (inprocess === 0) return
      inprocess = 0
      cleanup(eperm)
    }
 
    function fileHashComplete () {
      if (inprocess === 0) return
      if (--inprocess) return
      if (tmpFileHash.digest('hex') === targetFileHash.digest('hex')) {
        return cleanup()
      } else {
        return cleanup(eperm)
      }
    }
  }
 
  function cleanup (err) {
    fs.unlink(writeStream.__atomicTmp, function () {
      if (err) {
        writeStream.emit('error', err)
        writeStream.emit('close')
      } else {
        end()
      }
    })
  }
 
  function end () {
    // We have to use our parent class directly because we suppress `finish`
    // events fired via our own emit method.
    Writable.prototype.emit.call(writeStream, 'finish')
 
    // Delay the close to provide the same temporal separation a physical
    // file operation would have– that is, the close event is emitted only
    // after the async close operation completes.
    setImmediate(function () {
      writeStream.emit('close')
    })
  }
}
 
function handleError (writeStream) {
  return function (er) {
    cleanupSync()
    writeStream.emit('error', er)
    writeStream.__atomicClosed = true
    writeStream.emit('close')
  }
  function cleanupSync () {
    try {
      fs.unlinkSync(writeStream.__atomicTmp)
    } finally {
      return
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/

Statements: 7.77% (15 / 193)      Branches: 0% (0 / 181)      Functions: 0% (0 / 19)      Lines: 9.04% (15 / 166)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/
File Statements Branches Functions Lines
fstream-npm.js 7.77% (15 / 193) 0% (0 / 181) 0% (0 / 19) 9.04% (15 / 166)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/fstream-npm.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/fstream-npm.js

Statements: 7.77% (15 / 193)      Branches: 0% (0 / 181)      Functions: 0% (0 / 19)      Lines: 9.04% (15 / 166)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 3801 1 1 1   1   1   1                                                                                           1                                                                                                                   1                                                                                                                                                                                                                   1                               1                                                                               1                                       1                   1                                     1                                                                                                              
var Ignore = require('fstream-ignore')
var inherits = require('inherits')
var path = require('path')
var fs = require('fs')
 
module.exports = Packer
 
inherits(Packer, Ignore)
 
function Packer (props) {
  if (!(this instanceof Packer)) {
    return new Packer(props)
  }
 
  if (typeof props === 'string') {
    props = { path: props }
  }
 
  props.ignoreFiles = props.ignoreFiles || [ '.npmignore',
                                             '.gitignore',
                                             'package.json' ]
 
  Ignore.call(this, props)
 
  this.bundled = props.bundled
  this.bundleLinks = props.bundleLinks
  this.package = props.package
 
  // only do the magic bundling stuff for the node_modules folder that
  // lives right next to a package.json file.
  this.bundleMagic = this.parent &&
                     this.parent.packageRoot &&
                     this.basename === 'node_modules'
 
  // in a node_modules folder, resolve symbolic links to
  // bundled dependencies when creating the package.
  props.follow = this.follow = this.bundleMagic
  // console.error("follow?", this.path, props.follow)
 
  if (this === this.root ||
      this.parent &&
      this.parent.bundleMagic &&
      this.basename.charAt(0) !== '.') {
    this.readBundledLinks()
  }
 
  this.on('entryStat', function (entry, props) {
    // files should *always* get into tarballs
    // in a user-writable state, even if they're
    // being installed from some wackey vm-mounted
    // read-only filesystem.
    entry.mode = props.mode = props.mode | parseInt('0200', 8)
  })
}
 
Packer.prototype.readBundledLinks = function () {
  if (this._paused) {
    this.once('resume', this.addIgnoreFiles)
    return
  }
 
  this.pause()
  fs.readdir(this.path + '/node_modules', function (er, list) {
    // no harm if there's no bundle
    var l = list && list.length
    if (er || l === 0) return this.resume()
 
    var errState = null
    var then = function then (er) {
      if (errState) return
      if (er) {
        errState = er
        return this.resume()
      }
      if (--l === 0) return this.resume()
    }.bind(this)
 
    list.forEach(function (pkg) {
      if (pkg.charAt(0) === '.') return then()
      var pd = this.path + '/node_modules/' + pkg
 
      // scoped packages
      if (pkg.charAt(0) === '@') {
        fs.readdir(pd, function (er, slist) {
          var sl = slist && slist.length
          if (er || sl === 0) return then(er)
 
          l += sl
          slist.forEach(function (spkg) {
            if (spkg.charAt(0) === '.') return then()
            var spd = pd + '/' + spkg
            fs.realpath(spd, function (er, rp) {
              if (er) return then()
              this.bundleLinks = this.bundleLinks || {}
              this.bundleLinks[pkg + '/' + spkg] = rp
              then()
            }.bind(this))
          }, this)
          then()
        }.bind(this))
        return
      }
 
      fs.realpath(pd, function (er, rp) {
        if (er) return then()
        this.bundleLinks = this.bundleLinks || {}
        this.bundleLinks[pkg] = rp
        then()
      }.bind(this))
    }, this)
  }.bind(this))
}
 
Packer.prototype.applyIgnores = function (entry, partial, entryObj) {
  if (!entryObj || entryObj.type !== 'Directory') {
    // package.json files can never be ignored.
    if (entry === 'package.json') return true
 
    // readme files should never be ignored.
    if (entry.match(/^readme(\.[^\.]*)$/i)) return true
 
    // license files should never be ignored.
    if (entry.match(/^(license|licence)(\.[^\.]*)?$/i)) return true
 
    // copyright notice files should never be ignored.
    if (entry.match(/^(notice)(\.[^\.]*)?$/i)) return true
 
    // changelogs should never be ignored.
    if (entry.match(/^(changes|changelog|history)(\.[^\.]*)?$/i)) return true
  }
 
  // special rules.  see below.
  if (entry === 'node_modules' && this.packageRoot) return true
 
  // package.json main file should never be ignored.
  var mainFile = this.package && this.package.main
  if (mainFile && path.resolve(this.path, entry) === path.resolve(this.path, mainFile)) return true
 
  // some files are *never* allowed under any circumstances
  // (VCS folders, native build cruft, npm cruft, regular cruft)
  if (entry === '.git' ||
      entry === 'CVS' ||
      entry === '.svn' ||
      entry === '.hg' ||
      entry === '.lock-wscript' ||
      entry.match(/^\.wafpickle-[0-9]+$/) ||
      (this.parent && this.parent.packageRoot && this.basename === 'build' &&
       entry === 'config.gypi') ||
      entry === 'npm-debug.log' ||
      entry === '.npmrc' ||
      entry.match(/^\..*\.swp$/) ||
      entry === '.DS_Store' ||
      entry.match(/^\._/) ||
      entry.match(/^.*\.orig$/)
    ) {
    return false
  }
 
  // in a node_modules folder, we only include bundled dependencies
  // also, prevent packages in node_modules from being affected
  // by rules set in the containing package, so that
  // bundles don't get busted.
  // Also, once in a bundle, everything is installed as-is
  // To prevent infinite cycles in the case of cyclic deps that are
  // linked with npm link, even in a bundle, deps are only bundled
  // if they're not already present at a higher level.
  if (this.bundleMagic) {
    if (entry.charAt(0) === '@') {
      var firstSlash = entry.indexOf('/')
      // continue to list the packages in this scope
      if (firstSlash === -1) return true
 
      // bubbling up.  stop here and allow anything the bundled pkg allows
      if (entry.indexOf('/', firstSlash + 1) !== -1) return true
    }
    // bubbling up.  stop here and allow anything the bundled pkg allows
    else if (entry.indexOf('/') !== -1) return true
 
    // never include the .bin.  It's typically full of platform-specific
    // stuff like symlinks and .cmd files anyway.
    if (entry === '.bin') return false
 
    // the package root.
    var p = this.parent
    // the package before this one.
    var pp = p && p.parent
 
    // if this entry has already been bundled, and is a symlink,
    // and it is the *same* symlink as this one, then exclude it.
    if (pp && pp.bundleLinks && this.bundleLinks &&
        pp.bundleLinks[entry] &&
        pp.bundleLinks[entry] === this.bundleLinks[entry]) {
      return false
    }
 
    // since it's *not* a symbolic link, if we're *already* in a bundle,
    // then we should include everything.
    if (pp && pp.package && pp.basename === 'node_modules') {
      return true
    }
 
    // only include it at this point if it's a bundleDependency
    var bd = this.package && this.package.bundleDependencies
 
    if (bd && !Array.isArray(bd)) {
      throw new Error(this.package.name + '\'s `bundledDependencies` should ' +
                      'be an array')
    }
 
    var shouldBundle = bd && bd.indexOf(entry) !== -1
    // if we're not going to bundle it, then it doesn't count as a bundleLink
    // if (this.bundleLinks && !shouldBundle) delete this.bundleLinks[entry]
    return shouldBundle
  }
  // if (this.bundled) return true
 
  return Ignore.prototype.applyIgnores.call(this, entry, partial, entryObj)
}
 
Packer.prototype.addIgnoreFiles = function () {
  var entries = this.entries
  // if there's a .npmignore, then we do *not* want to
  // read the .gitignore.
  if (entries.indexOf('.npmignore') !== -1) {
    var i = entries.indexOf('.gitignore')
    if (i !== -1) {
      entries.splice(i, 1)
    }
  }
 
  this.entries = entries
 
  Ignore.prototype.addIgnoreFiles.call(this)
}
 
Packer.prototype.readRules = function (buf, e) {
  if (e !== 'package.json') {
    return Ignore.prototype.readRules.call(this, buf, e)
  }
 
  buf = buf.toString().trim()
 
  if (buf.length === 0) return []
 
  try {
    var p = this.package = JSON.parse(buf)
  } catch (er) {
    // just pretend it's a normal old file, not magic at all.
    return []
  }
 
  if (this === this.root) {
    this.bundleLinks = this.bundleLinks || {}
    this.bundleLinks[p.name] = this._path
  }
 
  this.packageRoot = true
  this.emit('package', p)
 
  // make bundle deps predictable
  if (p.bundledDependencies && !p.bundleDependencies) {
    p.bundleDependencies = p.bundledDependencies
    delete p.bundledDependencies
  }
 
  if (!p.files || !Array.isArray(p.files)) return []
 
  // ignore everything except what's in the files array.
  return ['*'].concat(p.files.map(function (f) {
    return '!' + f
  })).concat(p.files.map(function (f) {
    return '!' + f.replace(/\/+$/, '') + '/**'
  }))
}
 
Packer.prototype.getChildProps = function (stat) {
  var props = Ignore.prototype.getChildProps.call(this, stat)
 
  props.package = this.package
 
  props.bundled = this.bundled && this.bundled.slice(0)
  props.bundleLinks = this.bundleLinks &&
    Object.create(this.bundleLinks)
 
  // Directories have to be read as Packers
  // otherwise fstream.Reader will create a DirReader instead.
  if (stat.isDirectory()) {
    props.type = this.constructor
  }
 
  // only follow symbolic links directly in the node_modules folder.
  props.follow = false
  return props
}
 
var order = [
  'package.json',
  '.npmignore',
  '.gitignore',
  /^README(\.md)?$/,
  'LICENCE',
  'LICENSE',
  /\.js$/
]
 
Packer.prototype.sort = function (a, b) {
  for (var i = 0, l = order.length; i < l; i++) {
    var o = order[i]
    if (typeof o === 'string') {
      if (a === o) return -1
      if (b === o) return 1
    } else {
      if (a.match(o)) return -1
      if (b.match(o)) return 1
    }
  }
 
  // deps go in the back
  if (a === 'node_modules') return 1
  if (b === 'node_modules') return -1
 
  return Ignore.prototype.sort.call(this, a, b)
}
 
Packer.prototype.emitEntry = function (entry) {
  if (this._paused) {
    this.once('resume', this.emitEntry.bind(this, entry))
    return
  }
 
  // if there is a .gitignore, then we're going to
  // rename it to .npmignore in the output.
  if (entry.basename === '.gitignore') {
    entry.basename = '.npmignore'
    entry.path = path.resolve(entry.dirname, entry.basename)
  }
 
  // all *.gyp files are renamed to binding.gyp for node-gyp
  // but only when they are in the same folder as a package.json file.
  if (entry.basename.match(/\.gyp$/) &&
      this.entries.indexOf('package.json') !== -1) {
    entry.basename = 'binding.gyp'
    entry.path = path.resolve(entry.dirname, entry.basename)
  }
 
  // skip over symbolic links
  if (entry.type === 'SymbolicLink') {
    entry.abort()
    return
  }
 
  if (entry.type !== 'Directory') {
    // make it so that the folder in the tarball is named "package"
    var h = path.dirname((entry.root || entry).path)
    var t = entry.path.substr(h.length + 1).replace(/^[^\/\\]+/, 'package')
    var p = h + '/' + t
 
    entry.path = p
    entry.dirname = path.dirname(p)
    return Ignore.prototype.emitEntry.call(this, entry)
  }
 
  // we don't want empty directories to show up in package
  // tarballs.
  // don't emit entry events for dirs, but still walk through
  // and read them.  This means that we need to proxy up their
  // entry events so that those entries won't be missed, since
  // .pipe() doesn't do anythign special with "child" events, on
  // with "entry" events.
  var me = this
  entry.on('entry', function (e) {
    if (e.parent === entry) {
      e.parent = me
      me.emit('entry', e)
    }
  })
  entry.on('package', this.emit.bind(this, 'package'))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/

Statements: 13.16% (15 / 114)      Branches: 0% (0 / 86)      Functions: 0% (0 / 20)      Lines: 14.56% (15 / 103)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/
File Statements Branches Functions Lines
ignore.js 13.16% (15 / 114) 0% (0 / 86) 0% (0 / 20) 14.56% (15 / 103)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/ignore.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/ignore.js

Statements: 13.16% (15 / 114)      Branches: 0% (0 / 86)      Functions: 0% (0 / 20)      Lines: 14.56% (15 / 103)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277          1             1   1   1                                                                                                             1                                                             1             1                         1                               1             1                                                 1                             1                                                                                                                                           1                 1       1                
// Essentially, this is a fstream.DirReader class, but with a
// bit of special logic to read the specified sort of ignore files,
// and a filter that prevents it from picking up anything excluded
// by those files.
 
var Minimatch = require("minimatch").Minimatch
, fstream = require("fstream")
, DirReader = fstream.DirReader
, inherits = require("inherits")
, path = require("path")
, fs = require("fs")
 
module.exports = IgnoreReader
 
inherits(IgnoreReader, DirReader)
 
function IgnoreReader (props) {
  if (!(this instanceof IgnoreReader)) {
    return new IgnoreReader(props)
  }
 
  // must be a Directory type
  if (typeof props === "string") {
    props = { path: path.resolve(props) }
  }
 
  props.type = "Directory"
  props.Directory = true
 
  if (!props.ignoreFiles) props.ignoreFiles = [".ignore"]
  this.ignoreFiles = props.ignoreFiles
 
  this.ignoreRules = null
 
  // ensure that .ignore files always show up at the top of the list
  // that way, they can be read before proceeding to handle other
  // entries in that same folder
  if (props.sort) {
    this._sort = props.sort === "alpha" ? alphasort : props.sort
    props.sort = null
  }
 
  this.on("entries", function () {
    // if there are any ignore files in the list, then
    // pause and add them.
    // then, filter the list based on our ignoreRules
 
    var hasIg = this.entries.some(this.isIgnoreFile, this)
 
    if (!hasIg) return this.filterEntries()
 
    this.addIgnoreFiles()
  })
 
  // we filter entries before we know what they are.
  // however, directories have to be re-tested against
  // rules with a "/" appended, because "a/b/" will only
  // match if "a/b" is a dir, and not otherwise.
  this.on("_entryStat", function (entry, props) {
    var t = entry.basename
    if (!this.applyIgnores(entry.basename,
                           entry.type === "Directory",
                           entry)) {
      entry.abort()
    }
  }.bind(this))
 
  DirReader.call(this, props)
}
 
 
IgnoreReader.prototype.addIgnoreFiles = function () {
  if (this._paused) {
    this.once("resume", this.addIgnoreFiles)
    return
  }
  if (this._ignoreFilesAdded) return
  this._ignoreFilesAdded = true
 
  var newIg = this.entries.filter(this.isIgnoreFile, this)
  , count = newIg.length
  , errState = null
 
  if (!count) return
 
  this.pause()
 
  var then = function (er) {
    if (errState) return
    if (er) return this.emit("error", errState = er)
    if (-- count === 0) {
      this.filterEntries()
      this.resume()
    } else {
      this.addIgnoreFile(newIg[newIg.length - count], then)
    }
  }.bind(this)
 
  this.addIgnoreFile(newIg[0], then)
}
 
 
IgnoreReader.prototype.isIgnoreFile = function (e) {
  return e !== "." &&
         e !== ".." &&
         -1 !== this.ignoreFiles.indexOf(e)
}
 
 
IgnoreReader.prototype.getChildProps = function (stat) {
  var props = DirReader.prototype.getChildProps.call(this, stat)
  props.ignoreFiles = this.ignoreFiles
 
  // Directories have to be read as IgnoreReaders
  // otherwise fstream.Reader will create a DirReader instead.
  if (stat.isDirectory()) {
    props.type = this.constructor
  }
  return props
}
 
 
IgnoreReader.prototype.addIgnoreFile = function (e, cb) {
  // read the file, and then call addIgnoreRules
  // if there's an error, then tell the cb about it.
 
  var ig = path.resolve(this.path, e)
  fs.readFile(ig, function (er, data) {
    if (er) return cb(er)
 
    this.emit("ignoreFile", e, data)
    var rules = this.readRules(data, e)
    this.addIgnoreRules(rules, e)
    cb()
  }.bind(this))
}
 
 
IgnoreReader.prototype.readRules = function (buf, e) {
  return buf.toString().split(/\r?\n/)
}
 
 
// Override this to do fancier things, like read the
// "files" array from a package.json file or something.
IgnoreReader.prototype.addIgnoreRules = function (set, e) {
  // filter out anything obvious
  set = set.filter(function (s) {
    s = s.trim()
    return s && !s.match(/^#/)
  })
 
  // no rules to add!
  if (!set.length) return
 
  // now get a minimatch object for each one of these.
  // Note that we need to allow dot files by default, and
  // not switch the meaning of their exclusion
  var mmopt = { matchBase: true, dot: true, flipNegate: true }
  , mm = set.map(function (s) {
    var m = new Minimatch(s, mmopt)
    m.ignoreFile = e
    return m
  })
 
  if (!this.ignoreRules) this.ignoreRules = []
  this.ignoreRules.push.apply(this.ignoreRules, mm)
}
 
 
IgnoreReader.prototype.filterEntries = function () {
  // this exclusion is at the point where we know the list of
  // entries in the dir, but don't know what they are.  since
  // some of them *might* be directories, we have to run the
  // match in dir-mode as well, so that we'll pick up partials
  // of files that will be included later.  Anything included
  // at this point will be checked again later once we know
  // what it is.
  this.entries = this.entries.filter(function (entry) {
    // at this point, we don't know if it's a dir or not.
    return this.applyIgnores(entry) || this.applyIgnores(entry, true)
  }, this)
}
 
 
IgnoreReader.prototype.applyIgnores = function (entry, partial, obj) {
  var included = true
 
  // this = /a/b/c
  // entry = d
  // parent /a/b sees c/d
  if (this.parent && this.parent.applyIgnores) {
    var pt = this.basename + "/" + entry
    included = this.parent.applyIgnores(pt, partial)
  }
 
  // Negated Rules
  // Since we're *ignoring* things here, negating means that a file
  // is re-included, if it would have been excluded by a previous
  // rule.  So, negated rules are only relevant if the file
  // has been excluded.
  //
  // Similarly, if a file has been excluded, then there's no point
  // trying it against rules that have already been applied
  //
  // We're using the "flipnegate" flag here, which tells minimatch
  // to set the "negate" for our information, but still report
  // whether the core pattern was a hit or a miss.
 
  if (!this.ignoreRules) {
    return included
  }
 
  this.ignoreRules.forEach(function (rule) {
    // negation means inclusion
    if (rule.negate && included ||
        !rule.negate && !included) {
      // unnecessary
      return
    }
 
    // first, match against /foo/bar
    var match = rule.match("/" + entry)
 
    if (!match) {
      // try with the leading / trimmed off the test
      // eg: foo/bar instead of /foo/bar
      match = rule.match(entry)
    }
 
    // if the entry is a directory, then it will match
    // with a trailing slash. eg: /foo/bar/ or foo/bar/
    if (!match && partial) {
      match = rule.match("/" + entry + "/") ||
              rule.match(entry + "/")
    }
 
    // When including a file with a negated rule, it's
    // relevant if a directory partially matches, since
    // it may then match a file within it.
    // Eg, if you ignore /a, but !/a/b/c
    if (!match && rule.negate && partial) {
      match = rule.match("/" + entry, true) ||
              rule.match(entry, true)
    }
 
    if (match) {
      included = rule.negate
    }
  }, this)
 
  return included
}
 
 
IgnoreReader.prototype.sort = function (a, b) {
  var aig = this.ignoreFiles.indexOf(a) !== -1
  , big = this.ignoreFiles.indexOf(b) !== -1
 
  if (aig && !big) return -1
  if (big && !aig) return 1
  return this._sort(a, b)
}
 
IgnoreReader.prototype._sort = function (a, b) {
  return 0
}
 
function alphasort (a, b) {
  return a === b ? 0
       : a.toLowerCase() > b.toLowerCase() ? 1
       : a.toLowerCase() < b.toLowerCase() ? -1
       : a > b ? 1
       : -1
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/

Statements: 10.77% (46 / 427)      Branches: 0% (0 / 260)      Functions: 5.88% (2 / 34)      Lines: 11.41% (46 / 403)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/
File Statements Branches Functions Lines
minimatch.js 10.77% (46 / 427) 0% (0 / 260) 5.88% (2 / 34) 11.41% (46 / 403)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/minimatch.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/minimatch.js

Statements: 10.77% (46 / 427)      Branches: 0% (0 / 260)      Functions: 5.88% (2 / 34)      Lines: 11.41% (46 / 403)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 9251 1   1 1 1     1 1   1                   1     1         1       1     1     1 1 14 14         1   1 1             1                         1                               1         1                                   1                                                         1   1 1                                                                                                             1 1                                                         1       1   1                                                                       1 1 1                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1       1 1                                                                                         1                       1 1                                                                                                                       1                                                                                                                                                                                                                                                                                                                         1       1        
module.exports = minimatch
minimatch.Minimatch = Minimatch
 
var path = { sep: '/' }
try {
  path = require('path')
} catch (er) {}
 
var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
var expand = require('brace-expansion')
 
var plTypes = {
  '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  '?': { open: '(?:', close: ')?' },
  '+': { open: '(?:', close: ')+' },
  '*': { open: '(?:', close: ')*' },
  '@': { open: '(?:', close: ')' }
}
 
// any single thing other than /
// don't need to escape / when using new RegExp()
var qmark = '[^/]'
 
// * => any number of characters
var star = qmark + '*?'
 
// ** when dots are allowed.  Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
 
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
 
// characters that need to be escaped in RegExp.
var reSpecials = charSet('().*{}+?[]^$\\!')
 
// "abc" -> { a:true, b:true, c:true }
function charSet (s) {
  return s.split('').reduce(function (set, c) {
    set[c] = true
    return set
  }, {})
}
 
// normalizes slashes.
var slashSplit = /\/+/
 
minimatch.filter = filter
function filter (pattern, options) {
  options = options || {}
  return function (p, i, list) {
    return minimatch(p, pattern, options)
  }
}
 
function ext (a, b) {
  a = a || {}
  b = b || {}
  var t = {}
  Object.keys(b).forEach(function (k) {
    t[k] = b[k]
  })
  Object.keys(a).forEach(function (k) {
    t[k] = a[k]
  })
  return t
}
 
minimatch.defaults = function (def) {
  if (!def || !Object.keys(def).length) return minimatch
 
  var orig = minimatch
 
  var m = function minimatch (p, pattern, options) {
    return orig.minimatch(p, pattern, ext(def, options))
  }
 
  m.Minimatch = function Minimatch (pattern, options) {
    return new orig.Minimatch(pattern, ext(def, options))
  }
 
  return m
}
 
Minimatch.defaults = function (def) {
  if (!def || !Object.keys(def).length) return Minimatch
  return minimatch.defaults(def).Minimatch
}
 
function minimatch (p, pattern, options) {
  if (typeof pattern !== 'string') {
    throw new TypeError('glob pattern string required')
  }
 
  if (!options) options = {}
 
  // shortcut: comments match nothing.
  if (!options.nocomment && pattern.charAt(0) === '#') {
    return false
  }
 
  // "" only matches ""
  if (pattern.trim() === '') return p === ''
 
  return new Minimatch(pattern, options).match(p)
}
 
function Minimatch (pattern, options) {
  if (!(this instanceof Minimatch)) {
    return new Minimatch(pattern, options)
  }
 
  if (typeof pattern !== 'string') {
    throw new TypeError('glob pattern string required')
  }
 
  if (!options) options = {}
  pattern = pattern.trim()
 
  // windows support: need to use /, not \
  if (path.sep !== '/') {
    pattern = pattern.split(path.sep).join('/')
  }
 
  this.options = options
  this.set = []
  this.pattern = pattern
  this.regexp = null
  this.negate = false
  this.comment = false
  this.empty = false
 
  // make the set of regexps etc.
  this.make()
}
 
Minimatch.prototype.debug = function () {}
 
Minimatch.prototype.make = make
function make () {
  // don't do it more than once.
  if (this._made) return
 
  var pattern = this.pattern
  var options = this.options
 
  // empty patterns and comments match nothing.
  if (!options.nocomment && pattern.charAt(0) === '#') {
    this.comment = true
    return
  }
  if (!pattern) {
    this.empty = true
    return
  }
 
  // step 1: figure out negation, etc.
  this.parseNegate()
 
  // step 2: expand braces
  var set = this.globSet = this.braceExpand()
 
  if (options.debug) this.debug = console.error
 
  this.debug(this.pattern, set)
 
  // step 3: now we have a set, so turn each one into a series of path-portion
  // matching patterns.
  // These will be regexps, except in the case of "**", which is
  // set to the GLOBSTAR object for globstar behavior,
  // and will not contain any / characters
  set = this.globParts = set.map(function (s) {
    return s.split(slashSplit)
  })
 
  this.debug(this.pattern, set)
 
  // glob --> regexps
  set = set.map(function (s, si, set) {
    return s.map(this.parse, this)
  }, this)
 
  this.debug(this.pattern, set)
 
  // filter out everything that didn't compile properly.
  set = set.filter(function (s) {
    return s.indexOf(false) === -1
  })
 
  this.debug(this.pattern, set)
 
  this.set = set
}
 
Minimatch.prototype.parseNegate = parseNegate
function parseNegate () {
  var pattern = this.pattern
  var negate = false
  var options = this.options
  var negateOffset = 0
 
  if (options.nonegate) return
 
  for (var i = 0, l = pattern.length
    ; i < l && pattern.charAt(i) === '!'
    ; i++) {
    negate = !negate
    negateOffset++
  }
 
  if (negateOffset) this.pattern = pattern.substr(negateOffset)
  this.negate = negate
}
 
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = function (pattern, options) {
  return braceExpand(pattern, options)
}
 
Minimatch.prototype.braceExpand = braceExpand
 
function braceExpand (pattern, options) {
  if (!options) {
    if (this instanceof Minimatch) {
      options = this.options
    } else {
      options = {}
    }
  }
 
  pattern = typeof pattern === 'undefined'
    ? this.pattern : pattern
 
  if (typeof pattern === 'undefined') {
    throw new TypeError('undefined pattern')
  }
 
  if (options.nobrace ||
    !pattern.match(/\{.*\}/)) {
    // shortcut. no need to expand.
    return [pattern]
  }
 
  return expand(pattern)
}
 
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion.  Otherwise, any series
// of * is equivalent to a single *.  Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
Minimatch.prototype.parse = parse
var SUBPARSE = {}
function parse (pattern, isSub) {
  if (pattern.length > 1024 * 64) {
    throw new TypeError('pattern is too long')
  }
 
  var options = this.options
 
  // shortcuts
  if (!options.noglobstar && pattern === '**') return GLOBSTAR
  if (pattern === '') return ''
 
  var re = ''
  var hasMagic = !!options.nocase
  var escaping = false
  // ? => one single character
  var patternListStack = []
  var negativeLists = []
  var stateChar
  var inClass = false
  var reClassStart = -1
  var classStart = -1
  // . and .. never match anything that doesn't start with .,
  // even when options.dot is set.
  var patternStart = pattern.charAt(0) === '.' ? '' // anything
  // not (start or / followed by . or .. followed by / or end)
  : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  : '(?!\\.)'
  var self = this
 
  function clearStateChar () {
    if (stateChar) {
      // we had some state-tracking character
      // that wasn't consumed by this pass.
      switch (stateChar) {
        case '*':
          re += star
          hasMagic = true
        break
        case '?':
          re += qmark
          hasMagic = true
        break
        default:
          re += '\\' + stateChar
        break
      }
      self.debug('clearStateChar %j %j', stateChar, re)
      stateChar = false
    }
  }
 
  for (var i = 0, len = pattern.length, c
    ; (i < len) && (c = pattern.charAt(i))
    ; i++) {
    this.debug('%s\t%s %s %j', pattern, i, re, c)
 
    // skip over any that are escaped.
    if (escaping && reSpecials[c]) {
      re += '\\' + c
      escaping = false
      continue
    }
 
    switch (c) {
      case '/':
        // completely not allowed, even escaped.
        // Should already be path-split by now.
        return false
 
      case '\\':
        clearStateChar()
        escaping = true
      continue
 
      // the various stateChar values
      // for the "extglob" stuff.
      case '?':
      case '*':
      case '+':
      case '@':
      case '!':
        this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
 
        // all of those are literals inside a class, except that
        // the glob [!a] means [^a] in regexp
        if (inClass) {
          this.debug('  in class')
          if (c === '!' && i === classStart + 1) c = '^'
          re += c
          continue
        }
 
        // if we already have a stateChar, then it means
        // that there was something like ** or +? in there.
        // Handle the stateChar, then proceed with this one.
        self.debug('call clearStateChar %j', stateChar)
        clearStateChar()
        stateChar = c
        // if extglob is disabled, then +(asdf|foo) isn't a thing.
        // just clear the statechar *now*, rather than even diving into
        // the patternList stuff.
        if (options.noext) clearStateChar()
      continue
 
      case '(':
        if (inClass) {
          re += '('
          continue
        }
 
        if (!stateChar) {
          re += '\\('
          continue
        }
 
        patternListStack.push({
          type: stateChar,
          start: i - 1,
          reStart: re.length,
          open: plTypes[stateChar].open,
          close: plTypes[stateChar].close
        })
        // negation is (?:(?!js)[^/]*)
        re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
        this.debug('plType %j %j', stateChar, re)
        stateChar = false
      continue
 
      case ')':
        if (inClass || !patternListStack.length) {
          re += '\\)'
          continue
        }
 
        clearStateChar()
        hasMagic = true
        var pl = patternListStack.pop()
        // negation is (?:(?!js)[^/]*)
        // The others are (?:<pattern>)<type>
        re += pl.close
        if (pl.type === '!') {
          negativeLists.push(pl)
        }
        pl.reEnd = re.length
      continue
 
      case '|':
        if (inClass || !patternListStack.length || escaping) {
          re += '\\|'
          escaping = false
          continue
        }
 
        clearStateChar()
        re += '|'
      continue
 
      // these are mostly the same in regexp and glob
      case '[':
        // swallow any state-tracking char before the [
        clearStateChar()
 
        if (inClass) {
          re += '\\' + c
          continue
        }
 
        inClass = true
        classStart = i
        reClassStart = re.length
        re += c
      continue
 
      case ']':
        //  a right bracket shall lose its special
        //  meaning and represent itself in
        //  a bracket expression if it occurs
        //  first in the list.  -- POSIX.2 2.8.3.2
        if (i === classStart + 1 || !inClass) {
          re += '\\' + c
          escaping = false
          continue
        }
 
        // handle the case where we left a class open.
        // "[z-a]" is valid, equivalent to "\[z-a\]"
        if (inClass) {
          // split where the last [ was, make sure we don't have
          // an invalid re. if so, re-walk the contents of the
          // would-be class to re-translate any characters that
          // were passed through as-is
          // TODO: It would probably be faster to determine this
          // without a try/catch and a new RegExp, but it's tricky
          // to do safely.  For now, this is safe and works.
          var cs = pattern.substring(classStart + 1, i)
          try {
            RegExp('[' + cs + ']')
          } catch (er) {
            // not a valid class!
            var sp = this.parse(cs, SUBPARSE)
            re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
            hasMagic = hasMagic || sp[1]
            inClass = false
            continue
          }
        }
 
        // finish up the class.
        hasMagic = true
        inClass = false
        re += c
      continue
 
      default:
        // swallow any state char that wasn't consumed
        clearStateChar()
 
        if (escaping) {
          // no need
          escaping = false
        } else if (reSpecials[c]
          && !(c === '^' && inClass)) {
          re += '\\'
        }
 
        re += c
 
    } // switch
  } // for
 
  // handle the case where we left a class open.
  // "[abc" is valid, equivalent to "\[abc"
  if (inClass) {
    // split where the last [ was, and escape it
    // this is a huge pita.  We now have to re-walk
    // the contents of the would-be class to re-translate
    // any characters that were passed through as-is
    cs = pattern.substr(classStart + 1)
    sp = this.parse(cs, SUBPARSE)
    re = re.substr(0, reClassStart) + '\\[' + sp[0]
    hasMagic = hasMagic || sp[1]
  }
 
  // handle the case where we had a +( thing at the *end*
  // of the pattern.
  // each pattern list stack adds 3 chars, and we need to go through
  // and escape any | chars that were passed through as-is for the regexp.
  // Go through and escape them, taking care not to double-escape any
  // | chars that were already escaped.
  for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
    var tail = re.slice(pl.reStart + pl.open.length)
    this.debug('setting tail', re, pl)
    // maybe some even number of \, then maybe 1 \, followed by a |
    tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
      if (!$2) {
        // the | isn't already escaped, so escape it.
        $2 = '\\'
      }
 
      // need to escape all those slashes *again*, without escaping the
      // one that we need for escaping the | character.  As it works out,
      // escaping an even number of slashes can be done by simply repeating
      // it exactly after itself.  That's why this trick works.
      //
      // I am sorry that you have to see this.
      return $1 + $1 + $2 + '|'
    })
 
    this.debug('tail=%j\n   %s', tail, tail, pl, re)
    var t = pl.type === '*' ? star
      : pl.type === '?' ? qmark
      : '\\' + pl.type
 
    hasMagic = true
    re = re.slice(0, pl.reStart) + t + '\\(' + tail
  }
 
  // handle trailing things that only matter at the very end.
  clearStateChar()
  if (escaping) {
    // trailing \\
    re += '\\\\'
  }
 
  // only need to apply the nodot start if the re starts with
  // something that could conceivably capture a dot
  var addPatternStart = false
  switch (re.charAt(0)) {
    case '.':
    case '[':
    case '(': addPatternStart = true
  }
 
  // Hack to work around lack of negative lookbehind in JS
  // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  // like 'a.xyz.yz' doesn't match.  So, the first negative
  // lookahead, has to look ALL the way ahead, to the end of
  // the pattern.
  for (var n = negativeLists.length - 1; n > -1; n--) {
    var nl = negativeLists[n]
 
    var nlBefore = re.slice(0, nl.reStart)
    var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
    var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
    var nlAfter = re.slice(nl.reEnd)
 
    nlLast += nlAfter
 
    // Handle nested stuff like *(*.js|!(*.json)), where open parens
    // mean that we should *not* include the ) in the bit that is considered
    // "after" the negated section.
    var openParensBefore = nlBefore.split('(').length - 1
    var cleanAfter = nlAfter
    for (i = 0; i < openParensBefore; i++) {
      cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
    }
    nlAfter = cleanAfter
 
    var dollar = ''
    if (nlAfter === '' && isSub !== SUBPARSE) {
      dollar = '$'
    }
    var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
    re = newRe
  }
 
  // if the re is not "" at this point, then we need to make sure
  // it doesn't match against an empty path part.
  // Otherwise a/* will match a/, which it should not.
  if (re !== '' && hasMagic) {
    re = '(?=.)' + re
  }
 
  if (addPatternStart) {
    re = patternStart + re
  }
 
  // parsing just a piece of a larger pattern.
  if (isSub === SUBPARSE) {
    return [re, hasMagic]
  }
 
  // skip the regexp for non-magical patterns
  // unescape anything in it, though, so that it'll be
  // an exact match against a file etc.
  if (!hasMagic) {
    return globUnescape(pattern)
  }
 
  var flags = options.nocase ? 'i' : ''
  try {
    var regExp = new RegExp('^' + re + '$', flags)
  } catch (er) {
    // If it was an invalid regular expression, then it can't match
    // anything.  This trick looks for a character after the end of
    // the string, which is of course impossible, except in multi-line
    // mode, but it's not a /m regex.
    return new RegExp('$.')
  }
 
  regExp._glob = pattern
  regExp._src = re
 
  return regExp
}
 
minimatch.makeRe = function (pattern, options) {
  return new Minimatch(pattern, options || {}).makeRe()
}
 
Minimatch.prototype.makeRe = makeRe
function makeRe () {
  if (this.regexp || this.regexp === false) return this.regexp
 
  // at this point, this.set is a 2d array of partial
  // pattern strings, or "**".
  //
  // It's better to use .match().  This function shouldn't
  // be used, really, but it's pretty convenient sometimes,
  // when you just want to work with a regex.
  var set = this.set
 
  if (!set.length) {
    this.regexp = false
    return this.regexp
  }
  var options = this.options
 
  var twoStar = options.noglobstar ? star
    : options.dot ? twoStarDot
    : twoStarNoDot
  var flags = options.nocase ? 'i' : ''
 
  var re = set.map(function (pattern) {
    return pattern.map(function (p) {
      return (p === GLOBSTAR) ? twoStar
      : (typeof p === 'string') ? regExpEscape(p)
      : p._src
    }).join('\\\/')
  }).join('|')
 
  // must match entire pattern
  // ending in a * or ** will make it less strict.
  re = '^(?:' + re + ')$'
 
  // can match anything, as long as it's not this.
  if (this.negate) re = '^(?!' + re + ').*$'
 
  try {
    this.regexp = new RegExp(re, flags)
  } catch (ex) {
    this.regexp = false
  }
  return this.regexp
}
 
minimatch.match = function (list, pattern, options) {
  options = options || {}
  var mm = new Minimatch(pattern, options)
  list = list.filter(function (f) {
    return mm.match(f)
  })
  if (mm.options.nonull && !list.length) {
    list.push(pattern)
  }
  return list
}
 
Minimatch.prototype.match = match
function match (f, partial) {
  this.debug('match', f, this.pattern)
  // short-circuit in the case of busted things.
  // comments, etc.
  if (this.comment) return false
  if (this.empty) return f === ''
 
  if (f === '/' && partial) return true
 
  var options = this.options
 
  // windows: need to use /, not \
  if (path.sep !== '/') {
    f = f.split(path.sep).join('/')
  }
 
  // treat the test path as a set of pathparts.
  f = f.split(slashSplit)
  this.debug(this.pattern, 'split', f)
 
  // just ONE of the pattern sets in this.set needs to match
  // in order for it to be valid.  If negating, then just one
  // match means that we have failed.
  // Either way, return on the first hit.
 
  var set = this.set
  this.debug(this.pattern, 'set', set)
 
  // Find the basename of the path by looking for the last non-empty segment
  var filename
  var i
  for (i = f.length - 1; i >= 0; i--) {
    filename = f[i]
    if (filename) break
  }
 
  for (i = 0; i < set.length; i++) {
    var pattern = set[i]
    var file = f
    if (options.matchBase && pattern.length === 1) {
      file = [filename]
    }
    var hit = this.matchOne(file, pattern, partial)
    if (hit) {
      if (options.flipNegate) return true
      return !this.negate
    }
  }
 
  // didn't get any hits.  this is success if it's a negative
  // pattern, failure otherwise.
  if (options.flipNegate) return false
  return this.negate
}
 
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
Minimatch.prototype.matchOne = function (file, pattern, partial) {
  var options = this.options
 
  this.debug('matchOne',
    { 'this': this, file: file, pattern: pattern })
 
  this.debug('matchOne', file.length, pattern.length)
 
  for (var fi = 0,
      pi = 0,
      fl = file.length,
      pl = pattern.length
      ; (fi < fl) && (pi < pl)
      ; fi++, pi++) {
    this.debug('matchOne loop')
    var p = pattern[pi]
    var f = file[fi]
 
    this.debug(pattern, p, f)
 
    // should be impossible.
    // some invalid regexp stuff in the set.
    if (p === false) return false
 
    if (p === GLOBSTAR) {
      this.debug('GLOBSTAR', [pattern, p, f])
 
      // "**"
      // a/**/b/**/c would match the following:
      // a/b/x/y/z/c
      // a/x/y/z/b/c
      // a/b/x/b/x/c
      // a/b/c
      // To do this, take the rest of the pattern after
      // the **, and see if it would match the file remainder.
      // If so, return success.
      // If not, the ** "swallows" a segment, and try again.
      // This is recursively awful.
      //
      // a/**/b/**/c matching a/b/x/y/z/c
      // - a matches a
      // - doublestar
      //   - matchOne(b/x/y/z/c, b/**/c)
      //     - b matches b
      //     - doublestar
      //       - matchOne(x/y/z/c, c) -> no
      //       - matchOne(y/z/c, c) -> no
      //       - matchOne(z/c, c) -> no
      //       - matchOne(c, c) yes, hit
      var fr = fi
      var pr = pi + 1
      if (pr === pl) {
        this.debug('** at the end')
        // a ** at the end will just swallow the rest.
        // We have found a match.
        // however, it will not swallow /.x, unless
        // options.dot is set.
        // . and .. are *never* matched by **, for explosively
        // exponential reasons.
        for (; fi < fl; fi++) {
          if (file[fi] === '.' || file[fi] === '..' ||
            (!options.dot && file[fi].charAt(0) === '.')) return false
        }
        return true
      }
 
      // ok, let's see if we can swallow whatever we can.
      while (fr < fl) {
        var swallowee = file[fr]
 
        this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
 
        // XXX remove this slice.  Just pass the start index.
        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
          this.debug('globstar found match!', fr, fl, swallowee)
          // found a match.
          return true
        } else {
          // can't swallow "." or ".." ever.
          // can only swallow ".foo" when explicitly asked.
          if (swallowee === '.' || swallowee === '..' ||
            (!options.dot && swallowee.charAt(0) === '.')) {
            this.debug('dot detected!', file, fr, pattern, pr)
            break
          }
 
          // ** swallows a segment, and continue.
          this.debug('globstar swallow a segment, and continue')
          fr++
        }
      }
 
      // no match was found.
      // However, in partial mode, we can't say this is necessarily over.
      // If there's more *pattern* left, then
      if (partial) {
        // ran out of file
        this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
        if (fr === fl) return true
      }
      return false
    }
 
    // something other than **
    // non-magic patterns just have to match exactly
    // patterns with magic have been turned into regexps.
    var hit
    if (typeof p === 'string') {
      if (options.nocase) {
        hit = f.toLowerCase() === p.toLowerCase()
      } else {
        hit = f === p
      }
      this.debug('string match', p, f, hit)
    } else {
      hit = f.match(p)
      this.debug('pattern match', p, f, hit)
    }
 
    if (!hit) return false
  }
 
  // Note: ending in / means that we'll get a final ""
  // at the end of the pattern.  This can only match a
  // corresponding "" at the end of the file.
  // If the file ends in /, then it can only match a
  // a pattern that ends in /, unless the pattern just
  // doesn't have any more for it. But, a/b/ should *not*
  // match "a/b/*", even though "" matches against the
  // [^/]*? pattern, except in partial mode, where it might
  // simply not be reached yet.
  // However, a/b/ should still satisfy a/*
 
  // now either we fell off the end of the pattern, or we're done.
  if (fi === fl && pi === pl) {
    // ran out of pattern and filename at the same time.
    // an exact hit!
    return true
  } else if (fi === fl) {
    // ran out of file, but still had pattern left.
    // this is ok if we're doing the match as part of
    // a glob fs traversal.
    return partial
  } else if (pi === pl) {
    // ran out of pattern, still have file left.
    // this is only acceptable if we're on the very last
    // empty segment of a file with a trailing slash.
    // a/* should match a/b/
    var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
    return emptyFileEnd
  }
 
  // should be unreachable.
  throw new Error('wtf?')
}
 
// replace stuff like \* with *
function globUnescape (s) {
  return s.replace(/\\(.)/g, '$1')
}
 
function regExpEscape (s) {
  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/

Statements: 17.27% (19 / 110)      Branches: 0% (0 / 55)      Functions: 0% (0 / 13)      Lines: 17.59% (19 / 108)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/
File Statements Branches Functions Lines
index.js 17.27% (19 / 110) 0% (0 / 55) 0% (0 / 13) 17.59% (19 / 108)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/index.js

Statements: 17.27% (19 / 110)      Branches: 0% (0 / 55)      Functions: 0% (0 / 13)      Lines: 17.59% (19 / 108)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 2031 1   1   1 1 1 1 1   1           1               1                       1                                                     1                                 1       1     1       1     1       1                                                                                                                                                                                                              
var concatMap = require('concat-map');
var balanced = require('balanced-match');
 
module.exports = expandTop;
 
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
 
function numeric(str) {
  return parseInt(str, 10) == str
    ? parseInt(str, 10)
    : str.charCodeAt(0);
}
 
function escapeBraces(str) {
  return str.split('\\\\').join(escSlash)
            .split('\\{').join(escOpen)
            .split('\\}').join(escClose)
            .split('\\,').join(escComma)
            .split('\\.').join(escPeriod);
}
 
function unescapeBraces(str) {
  return str.split(escSlash).join('\\')
            .split(escOpen).join('{')
            .split(escClose).join('}')
            .split(escComma).join(',')
            .split(escPeriod).join('.');
}
 
 
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
  if (!str)
    return [''];
 
  var parts = [];
  var m = balanced('{', '}', str);
 
  if (!m)
    return str.split(',');
 
  var pre = m.pre;
  var body = m.body;
  var post = m.post;
  var p = pre.split(',');
 
  p[p.length-1] += '{' + body + '}';
  var postParts = parseCommaParts(post);
  if (post.length) {
    p[p.length-1] += postParts.shift();
    p.push.apply(p, postParts);
  }
 
  parts.push.apply(parts, p);
 
  return parts;
}
 
function expandTop(str) {
  if (!str)
    return [];
 
  // I don't know why Bash 4.3 does this, but it does.
  // Anything starting with {} will have the first two bytes preserved
  // but *only* at the top level, so {},a}b will not expand to anything,
  // but a{},b}c will be expanded to [a}c,abc].
  // One could argue that this is a bug in Bash, but since the goal of
  // this module is to match Bash's rules, we escape a leading {}
  if (str.substr(0, 2) === '{}') {
    str = '\\{\\}' + str.substr(2);
  }
 
  return expand(escapeBraces(str), true).map(unescapeBraces);
}
 
function identity(e) {
  return e;
}
 
function embrace(str) {
  return '{' + str + '}';
}
function isPadded(el) {
  return /^-?0\d/.test(el);
}
 
function lte(i, y) {
  return i <= y;
}
function gte(i, y) {
  return i >= y;
}
 
function expand(str, isTop) {
  var expansions = [];
 
  var m = balanced('{', '}', str);
  if (!m || /\$$/.test(m.pre)) return [str];
 
  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  var isSequence = isNumericSequence || isAlphaSequence;
  var isOptions = /^(.*,)+(.+)?$/.test(m.body);
  if (!isSequence && !isOptions) {
    // {a},b}
    if (m.post.match(/,.*\}/)) {
      str = m.pre + '{' + m.body + escClose + m.post;
      return expand(str);
    }
    return [str];
  }
 
  var n;
  if (isSequence) {
    n = m.body.split(/\.\./);
  } else {
    n = parseCommaParts(m.body);
    if (n.length === 1) {
      // x{{a,b}}y ==> x{a}y x{b}y
      n = expand(n[0], false).map(embrace);
      if (n.length === 1) {
        var post = m.post.length
          ? expand(m.post, false)
          : [''];
        return post.map(function(p) {
          return m.pre + n[0] + p;
        });
      }
    }
  }
 
  // at this point, n is the parts, and we know it's not a comma set
  // with a single entry.
 
  // no need to expand pre, since it is guaranteed to be free of brace-sets
  var pre = m.pre;
  var post = m.post.length
    ? expand(m.post, false)
    : [''];
 
  var N;
 
  if (isSequence) {
    var x = numeric(n[0]);
    var y = numeric(n[1]);
    var width = Math.max(n[0].length, n[1].length)
    var incr = n.length == 3
      ? Math.abs(numeric(n[2]))
      : 1;
    var test = lte;
    var reverse = y < x;
    if (reverse) {
      incr *= -1;
      test = gte;
    }
    var pad = n.some(isPadded);
 
    N = [];
 
    for (var i = x; test(i, y); i += incr) {
      var c;
      if (isAlphaSequence) {
        c = String.fromCharCode(i);
        if (c === '\\')
          c = '';
      } else {
        c = String(i);
        if (pad) {
          var need = width - c.length;
          if (need > 0) {
            var z = new Array(need + 1).join('0');
            if (i < 0)
              c = '-' + z + c.slice(1);
            else
              c = z + c;
          }
        }
      }
      N.push(c);
    }
  } else {
    N = concatMap(n, function(el) { return expand(el, false) });
  }
 
  for (var j = 0; j < N.length; j++) {
    for (var k = 0; k < post.length; k++) {
      var expansion = pre + N[j] + post[k];
      if (!isTop || isSequence || expansion)
        expansions.push(expansion);
    }
  }
 
  return expansions;
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/

Statements: 14.29% (5 / 35)      Branches: 0% (0 / 26)      Functions: 0% (0 / 3)      Lines: 15.15% (5 / 33)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/
File Statements Branches Functions Lines
index.js 14.29% (5 / 35) 0% (0 / 26) 0% (0 / 3) 15.15% (5 / 33)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js

Statements: 14.29% (5 / 35)      Branches: 0% (0 / 26)      Functions: 0% (0 / 3)      Lines: 15.15% (5 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601 1                             1         1 1                                                                          
module.exports = balanced;
function balanced(a, b, str) {
  if (a instanceof RegExp) a = maybeMatch(a, str);
  if (b instanceof RegExp) b = maybeMatch(b, str);
 
  var r = range(a, b, str);
 
  return r && {
    start: r[0],
    end: r[1],
    pre: str.slice(0, r[0]),
    body: str.slice(r[0] + a.length, r[1]),
    post: str.slice(r[1] + b.length)
  };
}
 
function maybeMatch(reg, str) {
  var m = str.match(reg);
  return m ? m[0] : null;
}
 
balanced.range = range;
function range(a, b, str) {
  var begs, beg, left, right, result;
  var ai = str.indexOf(a);
  var bi = str.indexOf(b, ai + 1);
  var i = ai;
 
  if (ai >= 0 && bi > 0) {
    begs = [];
    left = str.length;
 
    while (i >= 0 && !result) {
      if (i == ai) {
        begs.push(i);
        ai = str.indexOf(a, i + 1);
      } else if (begs.length == 1) {
        result = [ begs.pop(), bi ];
      } else {
        beg = begs.pop();
        if (beg < left) {
          left = beg;
          right = bi;
        }
 
        bi = str.indexOf(b, i + 1);
      }
 
      i = ai < bi && ai >= 0 ? ai : bi;
    }
 
    if (begs.length) {
      result = [ left, right ];
    }
  }
 
  return result;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/

Statements: 20% (2 / 10)      Branches: 25% (1 / 4)      Functions: 0% (0 / 2)      Lines: 22.22% (2 / 9)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/
File Statements Branches Functions Lines
index.js 20% (2 / 10) 25% (1 / 4) 0% (0 / 2) 22.22% (2 / 9)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream-npm/node_modules/fstream-ignore/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js

Statements: 20% (2 / 10)      Branches: 25% (1 / 4)      Functions: 0% (0 / 2)      Lines: 22.22% (2 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 151                   1        
module.exports = function (xs, fn) {
    var res = [];
    for (var i = 0; i < xs.length; i++) {
        var x = fn(xs[i], i);
        if (isArray(x)) res.push.apply(res, x);
        else res.push(x);
    }
    return res;
};
 
var isArray = Array.isArray || function (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/

Statements: 100% (16 / 16)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (16 / 16)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream/
File Statements Branches Functions Lines
fstream.js 100% (16 / 16) 100% (0 / 0) 100% (0 / 0) 100% (16 / 16)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/fstream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/fstream.js

Statements: 100% (16 / 16)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (16 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 371 1 1   1         1         1         1         1 1 1 1   1 1 1 1   1    
exports.Abstract = require('./lib/abstract.js')
exports.Reader = require('./lib/reader.js')
exports.Writer = require('./lib/writer.js')
 
exports.File = {
  Reader: require('./lib/file-reader.js'),
  Writer: require('./lib/file-writer.js')
}
 
exports.Dir = {
  Reader: require('./lib/dir-reader.js'),
  Writer: require('./lib/dir-writer.js')
}
 
exports.Link = {
  Reader: require('./lib/link-reader.js'),
  Writer: require('./lib/link-writer.js')
}
 
exports.Proxy = {
  Reader: require('./lib/proxy-reader.js'),
  Writer: require('./lib/proxy-writer.js')
}
 
exports.Reader.Dir = exports.DirReader = exports.Dir.Reader
exports.Reader.File = exports.FileReader = exports.File.Reader
exports.Reader.Link = exports.LinkReader = exports.Link.Reader
exports.Reader.Proxy = exports.ProxyReader = exports.Proxy.Reader
 
exports.Writer.Dir = exports.DirWriter = exports.Dir.Writer
exports.Writer.File = exports.FileWriter = exports.File.Writer
exports.Writer.Link = exports.LinkWriter = exports.Link.Writer
exports.Writer.Proxy = exports.ProxyWriter = exports.Proxy.Writer
 
exports.collect = require('./lib/collect.js')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/

Statements: 16.37% (173 / 1057)      Branches: 0.16% (1 / 610)      Functions: 0% (0 / 140)      Lines: 17.71% (173 / 977)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/
File Statements Branches Functions Lines
abstract.js 27.91% (12 / 43) 0% (0 / 32) 0% (0 / 9) 29.27% (12 / 41)
collect.js 12.24% (6 / 49) 0% (0 / 18) 0% (0 / 9) 14.63% (6 / 41)
dir-reader.js 11.89% (17 / 143) 0% (0 / 77) 0% (0 / 19) 12.78% (17 / 133)
dir-writer.js 15.91% (14 / 88) 0% (0 / 43) 0% (0 / 11) 16.87% (14 / 83)
file-reader.js 14.46% (12 / 83) 0% (0 / 50) 0% (0 / 9) 15.19% (12 / 79)
file-writer.js 16.92% (11 / 65) 0% (0 / 34) 0% (0 / 10) 18.97% (11 / 58)
get-type.js 11.76% (2 / 17) 0% (0 / 10) 0% (0 / 1) 12.5% (2 / 16)
link-reader.js 28.57% (8 / 28) 0% (0 / 14) 0% (0 / 4) 30.77% (8 / 26)
link-writer.js 23.64% (13 / 55) 0% (0 / 40) 0% (0 / 10) 26% (13 / 50)
proxy-reader.js 23.4% (11 / 47) 0% (0 / 14) 0% (0 / 9) 23.4% (11 / 47)
proxy-writer.js 22.03% (13 / 59) 0% (0 / 18) 0% (0 / 9) 22.41% (13 / 58)
reader.js 12.95% (18 / 139) 0% (0 / 98) 0% (0 / 11) 13.53% (18 / 133)
writer.js 14.94% (36 / 241) 0.62% (1 / 162) 0% (0 / 29) 16.98% (36 / 212)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/abstract.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/abstract.js

Statements: 27.91% (12 / 43)      Branches: 0% (0 / 32)      Functions: 0% (0 / 9)      Lines: 29.27% (12 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87    1   1 1   1       1   1                 1         1   1                                                   1       1           1                                          
// the parent class for all fstreams.
 
module.exports = Abstract
 
var Stream = require('stream').Stream
var inherits = require('inherits')
 
function Abstract () {
  Stream.call(this)
}
 
inherits(Abstract, Stream)
 
Abstract.prototype.on = function (ev, fn) {
  if (ev === 'ready' && this.ready) {
    process.nextTick(fn.bind(this))
  } else {
    Stream.prototype.on.call(this, ev, fn)
  }
  return this
}
 
Abstract.prototype.abort = function () {
  this._aborted = true
  this.emit('abort')
}
 
Abstract.prototype.destroy = function () {}
 
Abstract.prototype.warn = function (msg, code) {
  var self = this
  var er = decorate(msg, code, self)
  if (!self.listeners('warn')) {
    console.error('%s %s\n' +
    'path = %s\n' +
    'syscall = %s\n' +
    'fstream_type = %s\n' +
    'fstream_path = %s\n' +
    'fstream_unc_path = %s\n' +
    'fstream_class = %s\n' +
    'fstream_stack =\n%s\n',
      code || 'UNKNOWN',
      er.stack,
      er.path,
      er.syscall,
      er.fstream_type,
      er.fstream_path,
      er.fstream_unc_path,
      er.fstream_class,
      er.fstream_stack.join('\n'))
  } else {
    self.emit('warn', er)
  }
}
 
Abstract.prototype.info = function (msg, code) {
  this.emit('info', msg, code)
}
 
Abstract.prototype.error = function (msg, code, th) {
  var er = decorate(msg, code, this)
  if (th) throw er
  else this.emit('error', er)
}
 
function decorate (er, code, self) {
  if (!(er instanceof Error)) er = new Error(er)
  er.code = er.code || code
  er.path = er.path || self.path
  er.fstream_type = er.fstream_type || self.type
  er.fstream_path = er.fstream_path || self.path
  if (self._path !== self.path) {
    er.fstream_unc_path = er.fstream_unc_path || self._path
  }
  if (self.linkpath) {
    er.fstream_linkpath = er.fstream_linkpath || self.linkpath
  }
  er.fstream_class = er.fstream_class || self.constructor.name
  er.fstream_stack = er.fstream_stack ||
    new Error().stack.split(/\n/).slice(3).map(function (s) {
      return s.replace(/^ {4}at /, '')
    })
 
  return er
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/collect.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/collect.js

Statements: 12.24% (6 / 49)      Branches: 0% (0 / 18)      Functions: 0% (0 / 9)      Lines: 14.63% (6 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 721   1                     1               1           1                                             1                                          
module.exports = collect
 
function collect (stream) {
  if (stream._collected) return
 
  if (stream._paused) return stream.on('resume', collect.bind(null, stream))
 
  stream._collected = true
  stream.pause()
 
  stream.on('data', save)
  stream.on('end', save)
  var buf = []
  function save (b) {
    if (typeof b === 'string') b = new Buffer(b)
    if (Buffer.isBuffer(b) && !b.length) return
    buf.push(b)
  }
 
  stream.on('entry', saveEntry)
  var entryBuffer = []
  function saveEntry (e) {
    collect(e)
    entryBuffer.push(e)
  }
 
  stream.on('proxy', proxyPause)
  function proxyPause (p) {
    p.pause()
  }
 
  // replace the pipe method with a new version that will
  // unlock the buffered stuff.  if you just call .pipe()
  // without a destination, then it'll re-play the events.
  stream.pipe = (function (orig) {
    return function (dest) {
      // console.error(' === open the pipes', dest && dest.path)
 
      // let the entries flow through one at a time.
      // Once they're all done, then we can resume completely.
      var e = 0
      ;(function unblockEntry () {
        var entry = entryBuffer[e++]
        // console.error(" ==== unblock entry", entry && entry.path)
        if (!entry) return resume()
        entry.on('end', unblockEntry)
        if (dest) dest.add(entry)
        else stream.emit('entry', entry)
      })()
 
      function resume () {
        stream.removeListener('entry', saveEntry)
        stream.removeListener('data', save)
        stream.removeListener('end', save)
 
        stream.pipe = orig
        if (dest) stream.pipe(dest)
 
        buf.forEach(function (b) {
          if (b) stream.emit('data', b)
          else stream.emit('end')
        })
 
        stream.resume()
      }
 
      return dest
    }
  })(stream.pipe)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/dir-reader.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/dir-reader.js

Statements: 11.89% (17 / 143)      Branches: 0% (0 / 77)      Functions: 0% (0 / 19)      Lines: 12.78% (17 / 133)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254        1   1 1 1 1 1   1   1                                             1                                 1                     1                                                                                                                                                                                                   1                                                                   1                   1                       1                     1                                   1          
// A thing that emits "entry" events with Reader objects
// Pausing it causes it to stop emitting entry events, and also
// pauses the current entry if there is one.
 
module.exports = DirReader
 
var fs = require('graceful-fs')
var inherits = require('inherits')
var path = require('path')
var Reader = require('./reader.js')
var assert = require('assert').ok
 
inherits(DirReader, Reader)
 
function DirReader (props) {
  var self = this
  if (!(self instanceof DirReader)) {
    throw new Error('DirReader must be called as constructor.')
  }
 
  // should already be established as a Directory type
  if (props.type !== 'Directory' || !props.Directory) {
    throw new Error('Non-directory type ' + props.type)
  }
 
  self.entries = null
  self._index = -1
  self._paused = false
  self._length = -1
 
  if (props.sort) {
    this.sort = props.sort
  }
 
  Reader.call(this, props)
}
 
DirReader.prototype._getEntries = function () {
  var self = this
 
  // race condition.  might pause() before calling _getEntries,
  // and then resume, and try to get them a second time.
  if (self._gotEntries) return
  self._gotEntries = true
 
  fs.readdir(self._path, function (er, entries) {
    if (er) return self.error(er)
 
    self.entries = entries
 
    self.emit('entries', entries)
    if (self._paused) self.once('resume', processEntries)
    else processEntries()
 
    function processEntries () {
      self._length = self.entries.length
      if (typeof self.sort === 'function') {
        self.entries = self.entries.sort(self.sort.bind(self))
      }
      self._read()
    }
  })
}
 
// start walking the dir, and emit an "entry" event for each one.
DirReader.prototype._read = function () {
  var self = this
 
  if (!self.entries) return self._getEntries()
 
  if (self._paused || self._currentEntry || self._aborted) {
    // console.error('DR paused=%j, current=%j, aborted=%j', self._paused, !!self._currentEntry, self._aborted)
    return
  }
 
  self._index++
  if (self._index >= self.entries.length) {
    if (!self._ended) {
      self._ended = true
      self.emit('end')
      self.emit('close')
    }
    return
  }
 
  // ok, handle this one, then.
 
  // save creating a proxy, by stat'ing the thing now.
  var p = path.resolve(self._path, self.entries[self._index])
  assert(p !== self._path)
  assert(self.entries[self._index])
 
  // set this to prevent trying to _read() again in the stat time.
  self._currentEntry = p
  fs[ self.props.follow ? 'stat' : 'lstat' ](p, function (er, stat) {
    if (er) return self.error(er)
 
    var who = self._proxy || self
 
    stat.path = p
    stat.basename = path.basename(p)
    stat.dirname = path.dirname(p)
    var childProps = self.getChildProps.call(who, stat)
    childProps.path = p
    childProps.basename = path.basename(p)
    childProps.dirname = path.dirname(p)
 
    var entry = Reader(childProps, stat)
 
    // console.error("DR Entry", p, stat.size)
 
    self._currentEntry = entry
 
    // "entry" events are for direct entries in a specific dir.
    // "child" events are for any and all children at all levels.
    // This nomenclature is not completely final.
 
    entry.on('pause', function (who) {
      if (!self._paused && !entry._disowned) {
        self.pause(who)
      }
    })
 
    entry.on('resume', function (who) {
      if (self._paused && !entry._disowned) {
        self.resume(who)
      }
    })
 
    entry.on('stat', function (props) {
      self.emit('_entryStat', entry, props)
      if (entry._aborted) return
      if (entry._paused) {
        entry.once('resume', function () {
          self.emit('entryStat', entry, props)
        })
      } else self.emit('entryStat', entry, props)
    })
 
    entry.on('ready', function EMITCHILD () {
      // console.error("DR emit child", entry._path)
      if (self._paused) {
        // console.error("  DR emit child - try again later")
        // pause the child, and emit the "entry" event once we drain.
        // console.error("DR pausing child entry")
        entry.pause(self)
        return self.once('resume', EMITCHILD)
      }
 
      // skip over sockets.  they can't be piped around properly,
      // so there's really no sense even acknowledging them.
      // if someone really wants to see them, they can listen to
      // the "socket" events.
      if (entry.type === 'Socket') {
        self.emit('socket', entry)
      } else {
        self.emitEntry(entry)
      }
    })
 
    var ended = false
    entry.on('close', onend)
    entry.on('disown', onend)
    function onend () {
      if (ended) return
      ended = true
      self.emit('childEnd', entry)
      self.emit('entryEnd', entry)
      self._currentEntry = null
      if (!self._paused) {
        self._read()
      }
    }
 
    // XXX Remove this.  Works in node as of 0.6.2 or so.
    // Long filenames should not break stuff.
    entry.on('error', function (er) {
      if (entry._swallowErrors) {
        self.warn(er)
        entry.emit('end')
        entry.emit('close')
      } else {
        self.emit('error', er)
      }
    })
 
    // proxy up some events.
    ;[
      'child',
      'childEnd',
      'warn'
    ].forEach(function (ev) {
      entry.on(ev, self.emit.bind(self, ev))
    })
  })
}
 
DirReader.prototype.disown = function (entry) {
  entry.emit('beforeDisown')
  entry._disowned = true
  entry.parent = entry.root = null
  if (entry === this._currentEntry) {
    this._currentEntry = null
  }
  entry.emit('disown')
}
 
DirReader.prototype.getChildProps = function () {
  return {
    depth: this.depth + 1,
    root: this.root || this,
    parent: this,
    follow: this.follow,
    filter: this.filter,
    sort: this.props.sort,
    hardlinks: this.props.hardlinks
  }
}
 
DirReader.prototype.pause = function (who) {
  var self = this
  if (self._paused) return
  who = who || self
  self._paused = true
  if (self._currentEntry && self._currentEntry.pause) {
    self._currentEntry.pause(who)
  }
  self.emit('pause', who)
}
 
DirReader.prototype.resume = function (who) {
  var self = this
  if (!self._paused) return
  who = who || self
 
  self._paused = false
  // console.error('DR Emit Resume', self._path)
  self.emit('resume', who)
  if (self._paused) {
    // console.error('DR Re-paused', self._path)
    return
  }
 
  if (self._currentEntry) {
    if (self._currentEntry.resume) self._currentEntry.resume(who)
  } else self._read()
}
 
DirReader.prototype.emitEntry = function (entry) {
  this.emit('entry', entry)
  this.emit('child', entry)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/dir-writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/dir-writer.js

Statements: 15.91% (14 / 88)      Branches: 0% (0 / 43)      Functions: 0% (0 / 11)      Lines: 16.87% (14 / 83)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176            1   1 1 1 1 1   1   1                             1                             1       1         1                                         1                                                                                                                                                                                 1                    
// It is expected that, when .add() returns false, the consumer
// of the DirWriter will pause until a "drain" event occurs. Note
// that this is *almost always going to be the case*, unless the
// thing being written is some sort of unsupported type, and thus
// skipped over.
 
module.exports = DirWriter
 
var Writer = require('./writer.js')
var inherits = require('inherits')
var mkdir = require('mkdirp')
var path = require('path')
var collect = require('./collect.js')
 
inherits(DirWriter, Writer)
 
function DirWriter (props) {
  var self = this
  if (!(self instanceof DirWriter)) {
    self.error('DirWriter must be called as constructor.', null, true)
  }
 
  // should already be established as a Directory type
  if (props.type !== 'Directory' || !props.Directory) {
    self.error('Non-directory type ' + props.type + ' ' +
      JSON.stringify(props), null, true)
  }
 
  Writer.call(this, props)
}
 
DirWriter.prototype._create = function () {
  var self = this
  mkdir(self._path, Writer.dirmode, function (er) {
    if (er) return self.error(er)
    // ready to start getting entries!
    self.ready = true
    self.emit('ready')
    self._process()
  })
}
 
// a DirWriter has an add(entry) method, but its .write() doesn't
// do anything.  Why a no-op rather than a throw?  Because this
// leaves open the door for writing directory metadata for
// gnu/solaris style dumpdirs.
DirWriter.prototype.write = function () {
  return true
}
 
DirWriter.prototype.end = function () {
  this._ended = true
  this._process()
}
 
DirWriter.prototype.add = function (entry) {
  var self = this
 
  // console.error('\tadd', entry._path, '->', self._path)
  collect(entry)
  if (!self.ready || self._currentEntry) {
    self._buffer.push(entry)
    return false
  }
 
  // create a new writer, and pipe the incoming entry into it.
  if (self._ended) {
    return self.error('add after end')
  }
 
  self._buffer.push(entry)
  self._process()
 
  return this._buffer.length === 0
}
 
DirWriter.prototype._process = function () {
  var self = this
 
  // console.error('DW Process p=%j', self._processing, self.basename)
 
  if (self._processing) return
 
  var entry = self._buffer.shift()
  if (!entry) {
    // console.error("DW Drain")
    self.emit('drain')
    if (self._ended) self._finish()
    return
  }
 
  self._processing = true
  // console.error("DW Entry", entry._path)
 
  self.emit('entry', entry)
 
  // ok, add this entry
  //
  // don't allow recursive copying
  var p = entry
  var pp
  do {
    pp = p._path || p.path
    if (pp === self.root._path || pp === self._path ||
      (pp && pp.indexOf(self._path) === 0)) {
      // console.error('DW Exit (recursive)', entry.basename, self._path)
      self._processing = false
      if (entry._collected) entry.pipe()
      return self._process()
    }
    p = p.parent
  } while (p)
 
  // console.error("DW not recursive")
 
  // chop off the entry's root dir, replace with ours
  var props = {
    parent: self,
    root: self.root || self,
    type: entry.type,
    depth: self.depth + 1
  }
 
  pp = entry._path || entry.path || entry.props.path
  if (entry.parent) {
    pp = pp.substr(entry.parent._path.length + 1)
  }
  // get rid of any ../../ shenanigans
  props.path = path.join(self.path, path.join('/', pp))
 
  // if i have a filter, the child should inherit it.
  props.filter = self.filter
 
  // all the rest of the stuff, copy over from the source.
  Object.keys(entry.props).forEach(function (k) {
    if (!props.hasOwnProperty(k)) {
      props[k] = entry.props[k]
    }
  })
 
  // not sure at this point what kind of writer this is.
  var child = self._currentChild = new Writer(props)
  child.on('ready', function () {
    // console.error("DW Child Ready", child.type, child._path)
    // console.error("  resuming", entry._path)
    entry.pipe(child)
    entry.resume()
  })
 
  // XXX Make this work in node.
  // Long filenames should not break stuff.
  child.on('error', function (er) {
    if (child._swallowErrors) {
      self.warn(er)
      child.emit('end')
      child.emit('close')
    } else {
      self.emit('error', er)
    }
  })
 
  // we fire _end internally *after* end, so that we don't move on
  // until any "end" listeners have had their chance to do stuff.
  child.on('close', onend)
  var ended = false
  function onend () {
    if (ended) return
    ended = true
    // console.error("* DW Child end", child.basename)
    self._currentChild = null
    self._processing = false
    self._process()
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/file-reader.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/file-reader.js

Statements: 14.46% (12 / 83)      Branches: 0% (0 / 50)      Functions: 0% (0 / 9)      Lines: 15.19% (12 / 79)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152    1   1 1 1 1 1   1   1                                       1                                                                                                               1                                                                                   1                   1                      
// Basically just a wrapper around an fs.ReadStream
 
module.exports = FileReader
 
var fs = require('graceful-fs')
var inherits = require('inherits')
var Reader = require('./reader.js')
var EOF = {EOF: true}
var CLOSE = {CLOSE: true}
 
inherits(FileReader, Reader)
 
function FileReader (props) {
  // console.error("    FR create", props.path, props.size, new Error().stack)
  var self = this
  if (!(self instanceof FileReader)) {
    throw new Error('FileReader must be called as constructor.')
  }
 
  // should already be established as a File type
  // XXX Todo: preserve hardlinks by tracking dev+inode+nlink,
  // with a HardLinkReader class.
  if (!((props.type === 'Link' && props.Link) ||
    (props.type === 'File' && props.File))) {
    throw new Error('Non-file type ' + props.type)
  }
 
  self._buffer = []
  self._bytesEmitted = 0
  Reader.call(self, props)
}
 
FileReader.prototype._getStream = function () {
  var self = this
  var stream = self._stream = fs.createReadStream(self._path, self.props)
 
  if (self.props.blksize) {
    stream.bufferSize = self.props.blksize
  }
 
  stream.on('open', self.emit.bind(self, 'open'))
 
  stream.on('data', function (c) {
    // console.error('\t\t%d %s', c.length, self.basename)
    self._bytesEmitted += c.length
    // no point saving empty chunks
    if (!c.length) {
      return
    } else if (self._paused || self._buffer.length) {
      self._buffer.push(c)
      self._read()
    } else self.emit('data', c)
  })
 
  stream.on('end', function () {
    if (self._paused || self._buffer.length) {
      // console.error('FR Buffering End', self._path)
      self._buffer.push(EOF)
      self._read()
    } else {
      self.emit('end')
    }
 
    if (self._bytesEmitted !== self.props.size) {
      self.error("Didn't get expected byte count\n" +
        'expect: ' + self.props.size + '\n' +
        'actual: ' + self._bytesEmitted)
    }
  })
 
  stream.on('close', function () {
    if (self._paused || self._buffer.length) {
      // console.error('FR Buffering Close', self._path)
      self._buffer.push(CLOSE)
      self._read()
    } else {
      // console.error('FR close 1', self._path)
      self.emit('close')
    }
  })
 
  stream.on('error', function (e) {
    self.emit('error', e)
  })
 
  self._read()
}
 
FileReader.prototype._read = function () {
  var self = this
  // console.error('FR _read', self._path)
  if (self._paused) {
    // console.error('FR _read paused', self._path)
    return
  }
 
  if (!self._stream) {
    // console.error('FR _getStream calling', self._path)
    return self._getStream()
  }
 
  // clear out the buffer, if there is one.
  if (self._buffer.length) {
    // console.error('FR _read has buffer', self._buffer.length, self._path)
    var buf = self._buffer
    for (var i = 0, l = buf.length; i < l; i++) {
      var c = buf[i]
      if (c === EOF) {
        // console.error('FR Read emitting buffered end', self._path)
        self.emit('end')
      } else if (c === CLOSE) {
        // console.error('FR Read emitting buffered close', self._path)
        self.emit('close')
      } else {
        // console.error('FR Read emitting buffered data', self._path)
        self.emit('data', c)
      }
 
      if (self._paused) {
        // console.error('FR Read Re-pausing at '+i, self._path)
        self._buffer = buf.slice(i)
        return
      }
    }
    self._buffer.length = 0
  }
// console.error("FR _read done")
// that's about all there is to it.
}
 
FileReader.prototype.pause = function (who) {
  var self = this
  // console.error('FR Pause', self._path)
  if (self._paused) return
  who = who || self
  self._paused = true
  if (self._stream) self._stream.pause()
  self.emit('pause', who)
}
 
FileReader.prototype.resume = function (who) {
  var self = this
  // console.error('FR Resume', self._path)
  if (!self._paused) return
  who = who || self
  self.emit('resume', who)
  self._paused = false
  if (self._stream) self._stream.resume()
  self._read()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/file-writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/file-writer.js

Statements: 16.92% (11 / 65)      Branches: 0% (0 / 34)      Functions: 0% (0 / 10)      Lines: 18.97% (11 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 1091   1 1 1 1   1   1                                 1                                                                 1                                                 1                         1                      
module.exports = FileWriter
 
var fs = require('graceful-fs')
var Writer = require('./writer.js')
var inherits = require('inherits')
var EOF = {}
 
inherits(FileWriter, Writer)
 
function FileWriter (props) {
  var self = this
  if (!(self instanceof FileWriter)) {
    throw new Error('FileWriter must be called as constructor.')
  }
 
  // should already be established as a File type
  if (props.type !== 'File' || !props.File) {
    throw new Error('Non-file type ' + props.type)
  }
 
  self._buffer = []
  self._bytesWritten = 0
 
  Writer.call(this, props)
}
 
FileWriter.prototype._create = function () {
  var self = this
  if (self._stream) return
 
  var so = {}
  if (self.props.flags) so.flags = self.props.flags
  so.mode = Writer.filemode
  if (self._old && self._old.blksize) so.bufferSize = self._old.blksize
 
  self._stream = fs.createWriteStream(self._path, so)
 
  self._stream.on('open', function () {
    // console.error("FW open", self._buffer, self._path)
    self.ready = true
    self._buffer.forEach(function (c) {
      if (c === EOF) self._stream.end()
      else self._stream.write(c)
    })
    self.emit('ready')
    // give this a kick just in case it needs it.
    self.emit('drain')
  })
 
  self._stream.on('error', function (er) { self.emit('error', er) })
 
  self._stream.on('drain', function () { self.emit('drain') })
 
  self._stream.on('close', function () {
    // console.error('\n\nFW Stream Close', self._path, self.size)
    self._finish()
  })
}
 
FileWriter.prototype.write = function (c) {
  var self = this
 
  self._bytesWritten += c.length
 
  if (!self.ready) {
    if (!Buffer.isBuffer(c) && typeof c !== 'string') {
      throw new Error('invalid write data')
    }
    self._buffer.push(c)
    return false
  }
 
  var ret = self._stream.write(c)
  // console.error('\t-- fw wrote, _stream says', ret, self._stream._queue.length)
 
  // allow 2 buffered writes, because otherwise there's just too
  // much stop and go bs.
  if (ret === false && self._stream._queue) {
    return self._stream._queue.length <= 2
  } else {
    return ret
  }
}
 
FileWriter.prototype.end = function (c) {
  var self = this
 
  if (c) self.write(c)
 
  if (!self.ready) {
    self._buffer.push(EOF)
    return false
  }
 
  return self._stream.end()
}
 
FileWriter.prototype._finish = function () {
  var self = this
  if (typeof self.size === 'number' && self._bytesWritten !== self.size) {
    self.error(
      'Did not get expected byte count.\n' +
      'expect: ' + self.size + '\n' +
      'actual: ' + self._bytesWritten)
  }
  Writer.prototype._finish.call(self)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/get-type.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/get-type.js

Statements: 11.76% (2 / 17)      Branches: 0% (0 / 10)      Functions: 0% (0 / 1)      Lines: 12.5% (2 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 351   1                                                                
module.exports = getType
 
function getType (st) {
  var types = [
    'Directory',
    'File',
    'SymbolicLink',
    'Link', // special for hardlinks from tarballs
    'BlockDevice',
    'CharacterDevice',
    'FIFO',
    'Socket'
  ]
  var type
 
  if (st.type && types.indexOf(st.type) !== -1) {
    st[st.type] = true
    return st.type
  }
 
  for (var i = 0, l = types.length; i < l; i++) {
    type = types[i]
    var is = st[type] || st['is' + type]
    if (typeof is === 'function') is = is.call(st)
    if (is) {
      st[type] = true
      st.type = type
      return type
    }
  }
 
  return null
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/link-reader.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/link-reader.js

Statements: 28.57% (8 / 28)      Branches: 0% (0 / 14)      Functions: 0% (0 / 4)      Lines: 30.77% (8 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55            1   1 1 1   1   1                                   1                   1                        
// Basically just a wrapper around an fs.readlink
//
// XXX: Enhance this to support the Link type, by keeping
// a lookup table of {<dev+inode>:<path>}, so that hardlinks
// can be preserved in tarballs.
 
module.exports = LinkReader
 
var fs = require('graceful-fs')
var inherits = require('inherits')
var Reader = require('./reader.js')
 
inherits(LinkReader, Reader)
 
function LinkReader (props) {
  var self = this
  if (!(self instanceof LinkReader)) {
    throw new Error('LinkReader must be called as constructor.')
  }
 
  if (!((props.type === 'Link' && props.Link) ||
    (props.type === 'SymbolicLink' && props.SymbolicLink))) {
    throw new Error('Non-link type ' + props.type)
  }
 
  Reader.call(self, props)
}
 
// When piping a LinkReader into a LinkWriter, we have to
// already have the linkpath property set, so that has to
// happen *before* the "ready" event, which means we need to
// override the _stat method.
LinkReader.prototype._stat = function (currentStat) {
  var self = this
  fs.readlink(self._path, function (er, linkpath) {
    if (er) return self.error(er)
    self.linkpath = self.props.linkpath = linkpath
    self.emit('linkpath', linkpath)
    Reader.prototype._stat.call(self, currentStat)
  })
}
 
LinkReader.prototype._read = function () {
  var self = this
  if (self._paused) return
  // basically just a no-op, since we got all the info we need
  // from the _stat method
  if (!self._ended) {
    self.emit('end')
    self.emit('close')
    self._ended = true
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/link-writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/link-writer.js

Statements: 23.64% (13 / 55)      Branches: 0% (0 / 40)      Functions: 0% (0 / 10)      Lines: 26% (13 / 50)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 971   1 1 1 1 1   1   1                                       1                                     1             1                                                 1           1                  
module.exports = LinkWriter
 
var fs = require('graceful-fs')
var Writer = require('./writer.js')
var inherits = require('inherits')
var path = require('path')
var rimraf = require('rimraf')
 
inherits(LinkWriter, Writer)
 
function LinkWriter (props) {
  var self = this
  if (!(self instanceof LinkWriter)) {
    throw new Error('LinkWriter must be called as constructor.')
  }
 
  // should already be established as a Link type
  if (!((props.type === 'Link' && props.Link) ||
    (props.type === 'SymbolicLink' && props.SymbolicLink))) {
    throw new Error('Non-link type ' + props.type)
  }
 
  if (props.linkpath === '') props.linkpath = '.'
  if (!props.linkpath) {
    self.error('Need linkpath property to create ' + props.type)
  }
 
  Writer.call(this, props)
}
 
LinkWriter.prototype._create = function () {
  // console.error(" LW _create")
  var self = this
  var hard = self.type === 'Link' || process.platform === 'win32'
  var link = hard ? 'link' : 'symlink'
  var lp = hard ? path.resolve(self.dirname, self.linkpath) : self.linkpath
 
  // can only change the link path by clobbering
  // For hard links, let's just assume that's always the case, since
  // there's no good way to read them if we don't already know.
  if (hard) return clobber(self, lp, link)
 
  fs.readlink(self._path, function (er, p) {
    // only skip creation if it's exactly the same link
    if (p && p === lp) return finish(self)
    clobber(self, lp, link)
  })
}
 
function clobber (self, lp, link) {
  rimraf(self._path, function (er) {
    if (er) return self.error(er)
    create(self, lp, link)
  })
}
 
function create (self, lp, link) {
  fs[link](lp, self._path, function (er) {
    // if this is a hard link, and we're in the process of writing out a
    // directory, it's very possible that the thing we're linking to
    // doesn't exist yet (especially if it was intended as a symlink),
    // so swallow ENOENT errors here and just soldier in.
    // Additionally, an EPERM or EACCES can happen on win32 if it's trying
    // to make a link to a directory.  Again, just skip it.
    // A better solution would be to have fs.symlink be supported on
    // windows in some nice fashion.
    if (er) {
      if ((er.code === 'ENOENT' ||
        er.code === 'EACCES' ||
        er.code === 'EPERM') && process.platform === 'win32') {
        self.ready = true
        self.emit('ready')
        self.emit('end')
        self.emit('close')
        self.end = self._finish = function () {}
      } else return self.error(er)
    }
    finish(self)
  })
}
 
function finish (self) {
  self.ready = true
  self.emit('ready')
  if (self._ended && !self._finished) self._finish()
}
 
LinkWriter.prototype.end = function () {
  // console.error("LW finish in end")
  this._ended = true
  if (this.ready) {
    this._finished = true
    this._finish()
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/proxy-reader.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/proxy-reader.js

Statements: 23.4% (11 / 47)      Branches: 0% (0 / 14)      Functions: 0% (0 / 9)      Lines: 23.4% (11 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97      1   1 1 1 1   1   1                         1                                           1                                                                                 1       1        
// A reader for when we don't yet know what kind of thing
// the thing is.
 
module.exports = ProxyReader
 
var Reader = require('./reader.js')
var getType = require('./get-type.js')
var inherits = require('inherits')
var fs = require('graceful-fs')
 
inherits(ProxyReader, Reader)
 
function ProxyReader (props) {
  var self = this
  if (!(self instanceof ProxyReader)) {
    throw new Error('ProxyReader must be called as constructor.')
  }
 
  self.props = props
  self._buffer = []
  self.ready = false
 
  Reader.call(self, props)
}
 
ProxyReader.prototype._stat = function () {
  var self = this
  var props = self.props
  // stat the thing to see what the proxy should be.
  var stat = props.follow ? 'stat' : 'lstat'
 
  fs[stat](props.path, function (er, current) {
    var type
    if (er || !current) {
      type = 'File'
    } else {
      type = getType(current)
    }
 
    props[type] = true
    props.type = self.type = type
 
    self._old = current
    self._addProxy(Reader(props, current))
  })
}
 
ProxyReader.prototype._addProxy = function (proxy) {
  var self = this
  if (self._proxyTarget) {
    return self.error('proxy already set')
  }
 
  self._proxyTarget = proxy
  proxy._proxy = self
 
  ;[
    'error',
    'data',
    'end',
    'close',
    'linkpath',
    'entry',
    'entryEnd',
    'child',
    'childEnd',
    'warn',
    'stat'
  ].forEach(function (ev) {
    // console.error('~~ proxy event', ev, self.path)
    proxy.on(ev, self.emit.bind(self, ev))
  })
 
  self.emit('proxy', proxy)
 
  proxy.on('ready', function () {
    // console.error("~~ proxy is ready!", self.path)
    self.ready = true
    self.emit('ready')
  })
 
  var calls = self._buffer
  self._buffer.length = 0
  calls.forEach(function (c) {
    proxy[c[0]].apply(proxy, c[1])
  })
}
 
ProxyReader.prototype.pause = function () {
  return this._proxyTarget ? this._proxyTarget.pause() : false
}
 
ProxyReader.prototype.resume = function () {
  return this._proxyTarget ? this._proxyTarget.resume() : false
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/proxy-writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/proxy-writer.js

Statements: 22.03% (13 / 59)      Branches: 0% (0 / 18)      Functions: 0% (0 / 9)      Lines: 22.41% (13 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113              1   1 1 1 1 1   1   1                       1                                           1                                                           1                       1                   1                  
// A writer for when we don't know what kind of thing
// the thing is.  That is, it's not explicitly set,
// so we're going to make it whatever the thing already
// is, or "File"
//
// Until then, collect all events.
 
module.exports = ProxyWriter
 
var Writer = require('./writer.js')
var getType = require('./get-type.js')
var inherits = require('inherits')
var collect = require('./collect.js')
var fs = require('fs')
 
inherits(ProxyWriter, Writer)
 
function ProxyWriter (props) {
  var self = this
  if (!(self instanceof ProxyWriter)) {
    throw new Error('ProxyWriter must be called as constructor.')
  }
 
  self.props = props
  self._needDrain = false
 
  Writer.call(self, props)
}
 
ProxyWriter.prototype._stat = function () {
  var self = this
  var props = self.props
  // stat the thing to see what the proxy should be.
  var stat = props.follow ? 'stat' : 'lstat'
 
  fs[stat](props.path, function (er, current) {
    var type
    if (er || !current) {
      type = 'File'
    } else {
      type = getType(current)
    }
 
    props[type] = true
    props.type = self.type = type
 
    self._old = current
    self._addProxy(Writer(props, current))
  })
}
 
ProxyWriter.prototype._addProxy = function (proxy) {
  // console.error("~~ set proxy", this.path)
  var self = this
  if (self._proxy) {
    return self.error('proxy already set')
  }
 
  self._proxy = proxy
  ;[
    'ready',
    'error',
    'close',
    'pipe',
    'drain',
    'warn'
  ].forEach(function (ev) {
    proxy.on(ev, self.emit.bind(self, ev))
  })
 
  self.emit('proxy', proxy)
 
  var calls = self._buffer
  calls.forEach(function (c) {
    // console.error("~~ ~~ proxy buffered call", c[0], c[1])
    proxy[c[0]].apply(proxy, c[1])
  })
  self._buffer.length = 0
  if (self._needsDrain) self.emit('drain')
}
 
ProxyWriter.prototype.add = function (entry) {
  // console.error("~~ proxy add")
  collect(entry)
 
  if (!this._proxy) {
    this._buffer.push(['add', [entry]])
    this._needDrain = true
    return false
  }
  return this._proxy.add(entry)
}
 
ProxyWriter.prototype.write = function (c) {
  // console.error('~~ proxy write')
  if (!this._proxy) {
    this._buffer.push(['write', [c]])
    this._needDrain = true
    return false
  }
  return this._proxy.write(c)
}
 
ProxyWriter.prototype.end = function (c) {
  // console.error('~~ proxy end')
  if (!this._proxy) {
    this._buffer.push(['end', [c]])
    return false
  }
  return this._proxy.end(c)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/reader.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/reader.js

Statements: 12.95% (18 / 139)      Branches: 0% (0 / 98)      Functions: 0% (0 / 11)      Lines: 13.53% (18 / 133)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 2571   1 1 1 1 1 1 1     1   1   1                                                                                                                                                                                                                             1               1               1                                                                                                                                                             1                               1             1               1        
module.exports = Reader
 
var fs = require('graceful-fs')
var Stream = require('stream').Stream
var inherits = require('inherits')
var path = require('path')
var getType = require('./get-type.js')
var hardLinks = Reader.hardLinks = {}
var Abstract = require('./abstract.js')
 
// Must do this *before* loading the child classes
inherits(Reader, Abstract)
 
var LinkReader = require('./link-reader.js')
 
function Reader (props, currentStat) {
  var self = this
  if (!(self instanceof Reader)) return new Reader(props, currentStat)
 
  if (typeof props === 'string') {
    props = { path: props }
  }
 
  // polymorphism.
  // call fstream.Reader(dir) to get a DirReader object, etc.
  // Note that, unlike in the Writer case, ProxyReader is going
  // to be the *normal* state of affairs, since we rarely know
  // the type of a file prior to reading it.
 
  var type
  var ClassType
 
  if (props.type && typeof props.type === 'function') {
    type = props.type
    ClassType = type
  } else {
    type = getType(props)
    ClassType = Reader
  }
 
  if (currentStat && !type) {
    type = getType(currentStat)
    props[type] = true
    props.type = type
  }
 
  switch (type) {
    case 'Directory':
      ClassType = require('./dir-reader.js')
      break
 
    case 'Link':
    // XXX hard links are just files.
    // However, it would be good to keep track of files' dev+inode
    // and nlink values, and create a HardLinkReader that emits
    // a linkpath value of the original copy, so that the tar
    // writer can preserve them.
    // ClassType = HardLinkReader
    // break
 
    case 'File':
      ClassType = require('./file-reader.js')
      break
 
    case 'SymbolicLink':
      ClassType = LinkReader
      break
 
    case 'Socket':
      ClassType = require('./socket-reader.js')
      break
 
    case null:
      ClassType = require('./proxy-reader.js')
      break
  }
 
  if (!(self instanceof ClassType)) {
    return new ClassType(props)
  }
 
  Abstract.call(self)
 
  if (!props.path) {
    self.error('Must provide a path', null, true)
  }
 
  self.readable = true
  self.writable = false
 
  self.type = type
  self.props = props
  self.depth = props.depth = props.depth || 0
  self.parent = props.parent || null
  self.root = props.root || (props.parent && props.parent.root) || self
 
  self._path = self.path = path.resolve(props.path)
  if (process.platform === 'win32') {
    self.path = self._path = self.path.replace(/\?/g, '_')
    if (self._path.length >= 260) {
      // how DOES one create files on the moon?
      // if the path has spaces in it, then UNC will fail.
      self._swallowErrors = true
      // if (self._path.indexOf(" ") === -1) {
      self._path = '\\\\?\\' + self.path.replace(/\//g, '\\')
    // }
    }
  }
  self.basename = props.basename = path.basename(self.path)
  self.dirname = props.dirname = path.dirname(self.path)
 
  // these have served their purpose, and are now just noisy clutter
  props.parent = props.root = null
 
  // console.error("\n\n\n%s setting size to", props.path, props.size)
  self.size = props.size
  self.filter = typeof props.filter === 'function' ? props.filter : null
  if (props.sort === 'alpha') props.sort = alphasort
 
  // start the ball rolling.
  // this will stat the thing, and then call self._read()
  // to start reading whatever it is.
  // console.error("calling stat", props.path, currentStat)
  self._stat(currentStat)
}
 
function alphasort (a, b) {
  return a === b ? 0
    : a.toLowerCase() > b.toLowerCase() ? 1
      : a.toLowerCase() < b.toLowerCase() ? -1
        : a > b ? 1
          : -1
}
 
Reader.prototype._stat = function (currentStat) {
  var self = this
  var props = self.props
  var stat = props.follow ? 'stat' : 'lstat'
  // console.error("Reader._stat", self._path, currentStat)
  if (currentStat) process.nextTick(statCb.bind(null, null, currentStat))
  else fs[stat](self._path, statCb)
 
  function statCb (er, props_) {
    // console.error("Reader._stat, statCb", self._path, props_, props_.nlink)
    if (er) return self.error(er)
 
    Object.keys(props_).forEach(function (k) {
      props[k] = props_[k]
    })
 
    // if it's not the expected size, then abort here.
    if (undefined !== self.size && props.size !== self.size) {
      return self.error('incorrect size')
    }
    self.size = props.size
 
    var type = getType(props)
    var handleHardlinks = props.hardlinks !== false
 
    // special little thing for handling hardlinks.
    if (handleHardlinks && type !== 'Directory' && props.nlink && props.nlink > 1) {
      var k = props.dev + ':' + props.ino
      // console.error("Reader has nlink", self._path, k)
      if (hardLinks[k] === self._path || !hardLinks[k]) {
        hardLinks[k] = self._path
      } else {
        // switch into hardlink mode.
        type = self.type = self.props.type = 'Link'
        self.Link = self.props.Link = true
        self.linkpath = self.props.linkpath = hardLinks[k]
        // console.error("Hardlink detected, switching mode", self._path, self.linkpath)
        // Setting __proto__ would arguably be the "correct"
        // approach here, but that just seems too wrong.
        self._stat = self._read = LinkReader.prototype._read
      }
    }
 
    if (self.type && self.type !== type) {
      self.error('Unexpected type: ' + type)
    }
 
    // if the filter doesn't pass, then just skip over this one.
    // still have to emit end so that dir-walking can move on.
    if (self.filter) {
      var who = self._proxy || self
      // special handling for ProxyReaders
      if (!self.filter.call(who, who, props)) {
        if (!self._disowned) {
          self.abort()
          self.emit('end')
          self.emit('close')
        }
        return
      }
    }
 
    // last chance to abort or disown before the flow starts!
    var events = ['_stat', 'stat', 'ready']
    var e = 0
    ;(function go () {
      if (self._aborted) {
        self.emit('end')
        self.emit('close')
        return
      }
 
      if (self._paused && self.type !== 'Directory') {
        self.once('resume', go)
        return
      }
 
      var ev = events[e++]
      if (!ev) {
        return self._read()
      }
      self.emit(ev, props)
      go()
    })()
  }
}
 
Reader.prototype.pipe = function (dest) {
  var self = this
  if (typeof dest.add === 'function') {
    // piping to a multi-compatible, and we've got directory entries.
    self.on('entry', function (entry) {
      var ret = dest.add(entry)
      if (ret === false) {
        self.pause()
      }
    })
  }
 
  // console.error("R Pipe apply Stream Pipe")
  return Stream.prototype.pipe.apply(this, arguments)
}
 
Reader.prototype.pause = function (who) {
  this._paused = true
  who = who || this
  this.emit('pause', who)
  if (this._stream) this._stream.pause(who)
}
 
Reader.prototype.resume = function (who) {
  this._paused = false
  who = who || this
  this.emit('resume', who)
  if (this._stream) this._stream.resume(who)
  this._read()
}
 
Reader.prototype._read = function () {
  this.error('Cannot read unknown type: ' + this.type)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/fstream/lib/writer.js

Statements: 14.94% (36 / 241)      Branches: 0.62% (1 / 162)      Functions: 0% (0 / 29)      Lines: 16.98% (36 / 212)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 3921   1 1 1 1 1 1 1 1     1   1 1   1 1 1 1         1                                                                                                                                                                         1                     1                 1                                                                 1                             1                             1                                       1                                                           1                                                                                                 1             1                                 1                         1                             1                                       1             1       1       1       1       1        
module.exports = Writer
 
var fs = require('graceful-fs')
var inherits = require('inherits')
var rimraf = require('rimraf')
var mkdir = require('mkdirp')
var path = require('path')
var umask = process.platform === 'win32' ? 0 : process.umask()
var getType = require('./get-type.js')
var Abstract = require('./abstract.js')
 
// Must do this *before* loading the child classes
inherits(Writer, Abstract)
 
Writer.dirmode = parseInt('0777', 8) & (~umask)
Writer.filemode = parseInt('0666', 8) & (~umask)
 
var DirWriter = require('./dir-writer.js')
var LinkWriter = require('./link-writer.js')
var FileWriter = require('./file-writer.js')
var ProxyWriter = require('./proxy-writer.js')
 
// props is the desired state.  current is optionally the current stat,
// provided here so that subclasses can avoid statting the target
// more than necessary.
function Writer (props, current) {
  var self = this
 
  if (typeof props === 'string') {
    props = { path: props }
  }
 
  // polymorphism.
  // call fstream.Writer(dir) to get a DirWriter object, etc.
  var type = getType(props)
  var ClassType = Writer
 
  switch (type) {
    case 'Directory':
      ClassType = DirWriter
      break
    case 'File':
      ClassType = FileWriter
      break
    case 'Link':
    case 'SymbolicLink':
      ClassType = LinkWriter
      break
    case null:
    default:
      // Don't know yet what type to create, so we wrap in a proxy.
      ClassType = ProxyWriter
      break
  }
 
  if (!(self instanceof ClassType)) return new ClassType(props)
 
  // now get down to business.
 
  Abstract.call(self)
 
  if (!props.path) self.error('Must provide a path', null, true)
 
  // props is what we want to set.
  // set some convenience properties as well.
  self.type = props.type
  self.props = props
  self.depth = props.depth || 0
  self.clobber = props.clobber === false ? props.clobber : true
  self.parent = props.parent || null
  self.root = props.root || (props.parent && props.parent.root) || self
 
  self._path = self.path = path.resolve(props.path)
  if (process.platform === 'win32') {
    self.path = self._path = self.path.replace(/\?/g, '_')
    if (self._path.length >= 260) {
      self._swallowErrors = true
      self._path = '\\\\?\\' + self.path.replace(/\//g, '\\')
    }
  }
  self.basename = path.basename(props.path)
  self.dirname = path.dirname(props.path)
  self.linkpath = props.linkpath || null
 
  props.parent = props.root = null
 
  // console.error("\n\n\n%s setting size to", props.path, props.size)
  self.size = props.size
 
  if (typeof props.mode === 'string') {
    props.mode = parseInt(props.mode, 8)
  }
 
  self.readable = false
  self.writable = true
 
  // buffer until ready, or while handling another entry
  self._buffer = []
  self.ready = false
 
  self.filter = typeof props.filter === 'function' ? props.filter : null
 
  // start the ball rolling.
  // this checks what's there already, and then calls
  // self._create() to call the impl-specific creation stuff.
  self._stat(current)
}
 
// Calling this means that it's something we can't create.
// Just assert that it's already there, otherwise raise a warning.
Writer.prototype._create = function () {
  var self = this
  fs[self.props.follow ? 'stat' : 'lstat'](self._path, function (er) {
    if (er) {
      return self.warn('Cannot create ' + self._path + '\n' +
        'Unsupported type: ' + self.type, 'ENOTSUP')
    }
    self._finish()
  })
}
 
Writer.prototype._stat = function (current) {
  var self = this
  var props = self.props
  var stat = props.follow ? 'stat' : 'lstat'
  var who = self._proxy || self
 
  if (current) statCb(null, current)
  else fs[stat](self._path, statCb)
 
  function statCb (er, current) {
    if (self.filter && !self.filter.call(who, who, current)) {
      self._aborted = true
      self.emit('end')
      self.emit('close')
      return
    }
 
    // if it's not there, great.  We'll just create it.
    // if it is there, then we'll need to change whatever differs
    if (er || !current) {
      return create(self)
    }
 
    self._old = current
    var currentType = getType(current)
 
    // if it's a type change, then we need to clobber or error.
    // if it's not a type change, then let the impl take care of it.
    if (currentType !== self.type) {
      return rimraf(self._path, function (er) {
        if (er) return self.error(er)
        self._old = null
        create(self)
      })
    }
 
    // otherwise, just handle in the app-specific way
    // this creates a fs.WriteStream, or mkdir's, or whatever
    create(self)
  }
}
 
function create (self) {
  // console.error("W create", self._path, Writer.dirmode)
 
  // XXX Need to clobber non-dirs that are in the way,
  // unless { clobber: false } in the props.
  mkdir(path.dirname(self._path), Writer.dirmode, function (er, made) {
    // console.error("W created", path.dirname(self._path), er)
    if (er) return self.error(er)
 
    // later on, we have to set the mode and owner for these
    self._madeDir = made
    return self._create()
  })
}
 
function endChmod (self, want, current, path, cb) {
  var wantMode = want.mode
  var chmod = want.follow || self.type !== 'SymbolicLink'
    ? 'chmod' : 'lchmod'
 
  if (!fs[chmod]) return cb()
  if (typeof wantMode !== 'number') return cb()
 
  var curMode = current.mode & parseInt('0777', 8)
  wantMode = wantMode & parseInt('0777', 8)
  if (wantMode === curMode) return cb()
 
  fs[chmod](path, wantMode, cb)
}
 
function endChown (self, want, current, path, cb) {
  // Don't even try it unless root.  Too easy to EPERM.
  if (process.platform === 'win32') return cb()
  if (!process.getuid || process.getuid() !== 0) return cb()
  if (typeof want.uid !== 'number' &&
    typeof want.gid !== 'number') return cb()
 
  if (current.uid === want.uid &&
    current.gid === want.gid) return cb()
 
  var chown = (self.props.follow || self.type !== 'SymbolicLink')
    ? 'chown' : 'lchown'
  if (!fs[chown]) return cb()
 
  if (typeof want.uid !== 'number') want.uid = current.uid
  if (typeof want.gid !== 'number') want.gid = current.gid
 
  fs[chown](path, want.uid, want.gid, cb)
}
 
function endUtimes (self, want, current, path, cb) {
  if (!fs.utimes || process.platform === 'win32') return cb()
 
  var utimes = (want.follow || self.type !== 'SymbolicLink')
    ? 'utimes' : 'lutimes'
 
  if (utimes === 'lutimes' && !fs[utimes]) {
    utimes = 'utimes'
  }
 
  if (!fs[utimes]) return cb()
 
  var curA = current.atime
  var curM = current.mtime
  var meA = want.atime
  var meM = want.mtime
 
  if (meA === undefined) meA = curA
  if (meM === undefined) meM = curM
 
  if (!isDate(meA)) meA = new Date(meA)
  if (!isDate(meM)) meA = new Date(meM)
 
  if (meA.getTime() === curA.getTime() &&
    meM.getTime() === curM.getTime()) return cb()
 
  fs[utimes](path, meA, meM, cb)
}
 
// XXX This function is beastly.  Break it up!
Writer.prototype._finish = function () {
  var self = this
 
  if (self._finishing) return
  self._finishing = true
 
  // console.error(" W Finish", self._path, self.size)
 
  // set up all the things.
  // At this point, we're already done writing whatever we've gotta write,
  // adding files to the dir, etc.
  var todo = 0
  var errState = null
  var done = false
 
  if (self._old) {
    // the times will almost *certainly* have changed.
    // adds the utimes syscall, but remove another stat.
    self._old.atime = new Date(0)
    self._old.mtime = new Date(0)
    // console.error(" W Finish Stale Stat", self._path, self.size)
    setProps(self._old)
  } else {
    var stat = self.props.follow ? 'stat' : 'lstat'
    // console.error(" W Finish Stating", self._path, self.size)
    fs[stat](self._path, function (er, current) {
      // console.error(" W Finish Stated", self._path, self.size, current)
      if (er) {
        // if we're in the process of writing out a
        // directory, it's very possible that the thing we're linking to
        // doesn't exist yet (especially if it was intended as a symlink),
        // so swallow ENOENT errors here and just soldier on.
        if (er.code === 'ENOENT' &&
          (self.type === 'Link' || self.type === 'SymbolicLink') &&
          process.platform === 'win32') {
          self.ready = true
          self.emit('ready')
          self.emit('end')
          self.emit('close')
          self.end = self._finish = function () {}
          return
        } else return self.error(er)
      }
      setProps(self._old = current)
    })
  }
 
  return
 
  function setProps (current) {
    todo += 3
    endChmod(self, self.props, current, self._path, next('chmod'))
    endChown(self, self.props, current, self._path, next('chown'))
    endUtimes(self, self.props, current, self._path, next('utimes'))
  }
 
  function next (what) {
    return function (er) {
      // console.error("   W Finish", what, todo)
      if (errState) return
      if (er) {
        er.fstream_finish_call = what
        return self.error(errState = er)
      }
      if (--todo > 0) return
      if (done) return
      done = true
 
      // we may still need to set the mode/etc. on some parent dirs
      // that were created previously.  delay end/close until then.
      if (!self._madeDir) return end()
      else endMadeDir(self, self._path, end)
 
      function end (er) {
        if (er) {
          er.fstream_finish_call = 'setupMadeDir'
          return self.error(er)
        }
        // all the props have been set, so we're completely done.
        self.emit('end')
        self.emit('close')
      }
    }
  }
}
 
function endMadeDir (self, p, cb) {
  var made = self._madeDir
  // everything *between* made and path.dirname(self._path)
  // needs to be set up.  Note that this may just be one dir.
  var d = path.dirname(p)
 
  endMadeDir_(self, d, function (er) {
    if (er) return cb(er)
    if (d === made) {
      return cb()
    }
    endMadeDir(self, d, cb)
  })
}
 
function endMadeDir_ (self, p, cb) {
  var dirProps = {}
  Object.keys(self.props).forEach(function (k) {
    dirProps[k] = self.props[k]
 
    // only make non-readable dirs if explicitly requested.
    if (k === 'mode' && self.type !== 'Directory') {
      dirProps[k] = dirProps[k] | parseInt('0111', 8)
    }
  })
 
  var todo = 3
  var errState = null
  fs.stat(p, function (er, current) {
    if (er) return cb(errState = er)
    endChmod(self, dirProps, current, p, next)
    endChown(self, dirProps, current, p, next)
    endUtimes(self, dirProps, current, p, next)
  })
 
  function next (er) {
    if (errState) return
    if (er) return cb(errState = er)
    if (--todo === 0) return cb()
  }
}
 
Writer.prototype.pipe = function () {
  this.error("Can't pipe from writable stream")
}
 
Writer.prototype.add = function () {
  this.error("Can't add to non-Directory type")
}
 
Writer.prototype.write = function () {
  return true
}
 
function objectToString (d) {
  return Object.prototype.toString.call(d)
}
 
function isDate (d) {
  return typeof d === 'object' && objectToString(d) === '[object Date]'
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/

Statements: 13.15% (114 / 867)      Branches: 0% (0 / 579)      Functions: 0% (0 / 72)      Lines: 13.18% (114 / 865)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/glob/
File Statements Branches Functions Lines
common.js 15.79% (24 / 152) 0% (0 / 104) 0% (0 / 16) 15.79% (24 / 152)
glob.js 12.9% (57 / 442) 0% (0 / 285) 0% (0 / 40) 12.95% (57 / 440)
sync.js 12.09% (33 / 273) 0% (0 / 190) 0% (0 / 16) 12.09% (33 / 273)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/common.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/common.js

Statements: 15.79% (24 / 152)      Branches: 0% (0 / 104)      Functions: 0% (0 / 16)      Lines: 15.79% (24 / 152)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 2421 1 1 1 1 1 1 1 1   1       1 1 1 1   1       1       1                       1                         1                                                                                                                                         1                                                                                                                 1                                               1                                         1                 1                  
exports.alphasort = alphasort
exports.alphasorti = alphasorti
exports.setopts = setopts
exports.ownProp = ownProp
exports.makeAbs = makeAbs
exports.finish = finish
exports.mark = mark
exports.isIgnored = isIgnored
exports.childrenIgnored = childrenIgnored
 
function ownProp (obj, field) {
  return Object.prototype.hasOwnProperty.call(obj, field)
}
 
var path = require("path")
var minimatch = require("minimatch")
var isAbsolute = require("path-is-absolute")
var Minimatch = minimatch.Minimatch
 
function alphasorti (a, b) {
  return a.toLowerCase().localeCompare(b.toLowerCase())
}
 
function alphasort (a, b) {
  return a.localeCompare(b)
}
 
function setupIgnores (self, options) {
  self.ignore = options.ignore || []
 
  if (!Array.isArray(self.ignore))
    self.ignore = [self.ignore]
 
  if (self.ignore.length) {
    self.ignore = self.ignore.map(ignoreMap)
  }
}
 
// ignore patterns are always in dot:true mode.
function ignoreMap (pattern) {
  var gmatcher = null
  if (pattern.slice(-3) === '/**') {
    var gpattern = pattern.replace(/(\/\*\*)+$/, '')
    gmatcher = new Minimatch(gpattern, { dot: true })
  }
 
  return {
    matcher: new Minimatch(pattern, { dot: true }),
    gmatcher: gmatcher
  }
}
 
function setopts (self, pattern, options) {
  if (!options)
    options = {}
 
  // base-matching: just use globstar for that.
  if (options.matchBase && -1 === pattern.indexOf("/")) {
    if (options.noglobstar) {
      throw new Error("base matching requires globstar")
    }
    pattern = "**/" + pattern
  }
 
  self.silent = !!options.silent
  self.pattern = pattern
  self.strict = options.strict !== false
  self.realpath = !!options.realpath
  self.realpathCache = options.realpathCache || Object.create(null)
  self.follow = !!options.follow
  self.dot = !!options.dot
  self.mark = !!options.mark
  self.nodir = !!options.nodir
  if (self.nodir)
    self.mark = true
  self.sync = !!options.sync
  self.nounique = !!options.nounique
  self.nonull = !!options.nonull
  self.nosort = !!options.nosort
  self.nocase = !!options.nocase
  self.stat = !!options.stat
  self.noprocess = !!options.noprocess
  self.absolute = !!options.absolute
 
  self.maxLength = options.maxLength || Infinity
  self.cache = options.cache || Object.create(null)
  self.statCache = options.statCache || Object.create(null)
  self.symlinks = options.symlinks || Object.create(null)
 
  setupIgnores(self, options)
 
  self.changedCwd = false
  var cwd = process.cwd()
  if (!ownProp(options, "cwd"))
    self.cwd = cwd
  else {
    self.cwd = path.resolve(options.cwd)
    self.changedCwd = self.cwd !== cwd
  }
 
  self.root = options.root || path.resolve(self.cwd, "/")
  self.root = path.resolve(self.root)
  if (process.platform === "win32")
    self.root = self.root.replace(/\\/g, "/")
 
  // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
  if (process.platform === "win32")
    self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
  self.nomount = !!options.nomount
 
  // disable comments and negation in Minimatch.
  // Note that they are not supported in Glob itself anyway.
  options.nonegate = true
  options.nocomment = true
 
  self.minimatch = new Minimatch(pattern, options)
  self.options = self.minimatch.options
}
 
function finish (self) {
  var nou = self.nounique
  var all = nou ? [] : Object.create(null)
 
  for (var i = 0, l = self.matches.length; i < l; i ++) {
    var matches = self.matches[i]
    if (!matches || Object.keys(matches).length === 0) {
      if (self.nonull) {
        // do like the shell, and spit out the literal glob
        var literal = self.minimatch.globSet[i]
        if (nou)
          all.push(literal)
        else
          all[literal] = true
      }
    } else {
      // had matches
      var m = Object.keys(matches)
      if (nou)
        all.push.apply(all, m)
      else
        m.forEach(function (m) {
          all[m] = true
        })
    }
  }
 
  if (!nou)
    all = Object.keys(all)
 
  if (!self.nosort)
    all = all.sort(self.nocase ? alphasorti : alphasort)
 
  // at *some* point we statted all of these
  if (self.mark) {
    for (var i = 0; i < all.length; i++) {
      all[i] = self._mark(all[i])
    }
    if (self.nodir) {
      all = all.filter(function (e) {
        var notDir = !(/\/$/.test(e))
        var c = self.cache[e] || self.cache[makeAbs(self, e)]
        if (notDir && c)
          notDir = c !== 'DIR' && !Array.isArray(c)
        return notDir
      })
    }
  }
 
  if (self.ignore.length)
    all = all.filter(function(m) {
      return !isIgnored(self, m)
    })
 
  self.found = all
}
 
function mark (self, p) {
  var abs = makeAbs(self, p)
  var c = self.cache[abs]
  var m = p
  if (c) {
    var isDir = c === 'DIR' || Array.isArray(c)
    var slash = p.slice(-1) === '/'
 
    if (isDir && !slash)
      m += '/'
    else if (!isDir && slash)
      m = m.slice(0, -1)
 
    if (m !== p) {
      var mabs = makeAbs(self, m)
      self.statCache[mabs] = self.statCache[abs]
      self.cache[mabs] = self.cache[abs]
    }
  }
 
  return m
}
 
// lotta situps...
function makeAbs (self, f) {
  var abs = f
  if (f.charAt(0) === '/') {
    abs = path.join(self.root, f)
  } else if (isAbsolute(f) || f === '') {
    abs = f
  } else if (self.changedCwd) {
    abs = path.resolve(self.cwd, f)
  } else {
    abs = path.resolve(f)
  }
 
  if (process.platform === 'win32')
    abs = abs.replace(/\\/g, '/')
 
  return abs
}
 
 
// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
function isIgnored (self, path) {
  if (!self.ignore.length)
    return false
 
  return self.ignore.some(function(item) {
    return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  })
}
 
function childrenIgnored (self, path) {
  if (!self.ignore.length)
    return false
 
  return self.ignore.some(function(item) {
    return !!(item.gmatcher && item.gmatcher.match(path))
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/glob.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/glob.js

Statements: 12.9% (57 / 442)      Branches: 0% (0 / 285)      Functions: 0% (0 / 40)      Lines: 12.95% (57 / 440)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794                                                                                1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1   1                         1 1     1   1                         1                                         1 1 1                                                                                                               1                           1                       1                           1           1                                                                   1       1       1         1             1                                               1                                                                                                                                           1             1                                                                                                                                                             1                                                                           1                               1                                 1                                                 1                 1                                           1                                                                                   1               1                                                                               1               1                                                             1                                                                                     1                               1                                              
// Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together.  This is PREFIX.
//   If there is no more remaining, then stat(PREFIX) and
//   add to matches if it succeeds.  END.
//
// If inGlobStar and PREFIX is symlink and points to dir
//   set ENTRIES = []
// else readdir(PREFIX) as ENTRIES
//   If fail, END
//
// with ENTRIES
//   If pattern[n] is GLOBSTAR
//     // handle the case where the globstar match is empty
//     // by pruning it out, and testing the resulting pattern
//     PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
//     // handle other cases.
//     for ENTRY in ENTRIES (not dotfiles)
//       // attach globstar + tail onto the entry
//       // Mark that this entry is a globstar match
//       PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
//
//   else // not globstar
//     for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
//       Test ENTRY against pattern[n]
//       If fails, continue
//       If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
//
// Caveat:
//   Cache all stats and readdirs results to minimize syscall.  Since all
//   we ever care about is existence and directory-ness, we can just keep
//   `true` for files, and [children,...] for directories, or `false` for
//   things that don't exist.
 
module.exports = glob
 
var fs = require('fs')
var rp = require('fs.realpath')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var inherits = require('inherits')
var EE = require('events').EventEmitter
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var globSync = require('./sync.js')
var common = require('./common.js')
var alphasort = common.alphasort
var alphasorti = common.alphasorti
var setopts = common.setopts
var ownProp = common.ownProp
var inflight = require('inflight')
var util = require('util')
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
 
var once = require('once')
 
function glob (pattern, options, cb) {
  if (typeof options === 'function') cb = options, options = {}
  if (!options) options = {}
 
  if (options.sync) {
    if (cb)
      throw new TypeError('callback provided to sync glob')
    return globSync(pattern, options)
  }
 
  return new Glob(pattern, options, cb)
}
 
glob.sync = globSync
var GlobSync = glob.GlobSync = globSync.GlobSync
 
// old api surface
glob.glob = glob
 
function extend (origin, add) {
  if (add === null || typeof add !== 'object') {
    return origin
  }
 
  var keys = Object.keys(add)
  var i = keys.length
  while (i--) {
    origin[keys[i]] = add[keys[i]]
  }
  return origin
}
 
glob.hasMagic = function (pattern, options_) {
  var options = extend({}, options_)
  options.noprocess = true
 
  var g = new Glob(pattern, options)
  var set = g.minimatch.set
 
  if (!pattern)
    return false
 
  if (set.length > 1)
    return true
 
  for (var j = 0; j < set[0].length; j++) {
    if (typeof set[0][j] !== 'string')
      return true
  }
 
  return false
}
 
glob.Glob = Glob
inherits(Glob, EE)
function Glob (pattern, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = null
  }
 
  if (options && options.sync) {
    if (cb)
      throw new TypeError('callback provided to sync glob')
    return new GlobSync(pattern, options)
  }
 
  if (!(this instanceof Glob))
    return new Glob(pattern, options, cb)
 
  setopts(this, pattern, options)
  this._didRealPath = false
 
  // process each pattern in the minimatch set
  var n = this.minimatch.set.length
 
  // The matches are stored as {<filename>: true,...} so that
  // duplicates are automagically pruned.
  // Later, we do an Object.keys() on these.
  // Keep them as a list so we can fill in when nonull is set.
  this.matches = new Array(n)
 
  if (typeof cb === 'function') {
    cb = once(cb)
    this.on('error', cb)
    this.on('end', function (matches) {
      cb(null, matches)
    })
  }
 
  var self = this
  var n = this.minimatch.set.length
  this._processing = 0
  this.matches = new Array(n)
 
  this._emitQueue = []
  this._processQueue = []
  this.paused = false
 
  if (this.noprocess)
    return this
 
  if (n === 0)
    return done()
 
  var sync = true
  for (var i = 0; i < n; i ++) {
    this._process(this.minimatch.set[i], i, false, done)
  }
  sync = false
 
  function done () {
    --self._processing
    if (self._processing <= 0) {
      if (sync) {
        process.nextTick(function () {
          self._finish()
        })
      } else {
        self._finish()
      }
    }
  }
}
 
Glob.prototype._finish = function () {
  assert(this instanceof Glob)
  if (this.aborted)
    return
 
  if (this.realpath && !this._didRealpath)
    return this._realpath()
 
  common.finish(this)
  this.emit('end', this.found)
}
 
Glob.prototype._realpath = function () {
  if (this._didRealpath)
    return
 
  this._didRealpath = true
 
  var n = this.matches.length
  if (n === 0)
    return this._finish()
 
  var self = this
  for (var i = 0; i < this.matches.length; i++)
    this._realpathSet(i, next)
 
  function next () {
    if (--n === 0)
      self._finish()
  }
}
 
Glob.prototype._realpathSet = function (index, cb) {
  var matchset = this.matches[index]
  if (!matchset)
    return cb()
 
  var found = Object.keys(matchset)
  var self = this
  var n = found.length
 
  if (n === 0)
    return cb()
 
  var set = this.matches[index] = Object.create(null)
  found.forEach(function (p, i) {
    // If there's a problem with the stat, then it means that
    // one or more of the links in the realpath couldn't be
    // resolved.  just return the abs value in that case.
    p = self._makeAbs(p)
    rp.realpath(p, self.realpathCache, function (er, real) {
      if (!er)
        set[real] = true
      else if (er.syscall === 'stat')
        set[p] = true
      else
        self.emit('error', er) // srsly wtf right here
 
      if (--n === 0) {
        self.matches[index] = set
        cb()
      }
    })
  })
}
 
Glob.prototype._mark = function (p) {
  return common.mark(this, p)
}
 
Glob.prototype._makeAbs = function (f) {
  return common.makeAbs(this, f)
}
 
Glob.prototype.abort = function () {
  this.aborted = true
  this.emit('abort')
}
 
Glob.prototype.pause = function () {
  if (!this.paused) {
    this.paused = true
    this.emit('pause')
  }
}
 
Glob.prototype.resume = function () {
  if (this.paused) {
    this.emit('resume')
    this.paused = false
    if (this._emitQueue.length) {
      var eq = this._emitQueue.slice(0)
      this._emitQueue.length = 0
      for (var i = 0; i < eq.length; i ++) {
        var e = eq[i]
        this._emitMatch(e[0], e[1])
      }
    }
    if (this._processQueue.length) {
      var pq = this._processQueue.slice(0)
      this._processQueue.length = 0
      for (var i = 0; i < pq.length; i ++) {
        var p = pq[i]
        this._processing--
        this._process(p[0], p[1], p[2], p[3])
      }
    }
  }
}
 
Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  assert(this instanceof Glob)
  assert(typeof cb === 'function')
 
  if (this.aborted)
    return
 
  this._processing++
  if (this.paused) {
    this._processQueue.push([pattern, index, inGlobStar, cb])
    return
  }
 
  //console.error('PROCESS %d', this._processing, pattern)
 
  // Get the first [n] parts of pattern that are all strings.
  var n = 0
  while (typeof pattern[n] === 'string') {
    n ++
  }
  // now n is the index of the first one that is *not* a string.
 
  // see if there's anything else
  var prefix
  switch (n) {
    // if not, then this is rather simple
    case pattern.length:
      this._processSimple(pattern.join('/'), index, cb)
      return
 
    case 0:
      // pattern *starts* with some non-trivial item.
      // going to readdir(cwd), but not include the prefix in matches.
      prefix = null
      break
 
    default:
      // pattern has some string bits in the front.
      // whatever it starts with, whether that's 'absolute' like /foo/bar,
      // or 'relative' like '../baz'
      prefix = pattern.slice(0, n).join('/')
      break
  }
 
  var remain = pattern.slice(n)
 
  // get the list of entries.
  var read
  if (prefix === null)
    read = '.'
  else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
    if (!prefix || !isAbsolute(prefix))
      prefix = '/' + prefix
    read = prefix
  } else
    read = prefix
 
  var abs = this._makeAbs(read)
 
  //if ignored, skip _processing
  if (childrenIgnored(this, read))
    return cb()
 
  var isGlobStar = remain[0] === minimatch.GLOBSTAR
  if (isGlobStar)
    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
  else
    this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
 
Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  var self = this
  this._readdir(abs, inGlobStar, function (er, entries) {
    return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  })
}
 
Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
 
  // if the abs isn't a dir, then nothing can match!
  if (!entries)
    return cb()
 
  // It will only match dot entries if it starts with a dot, or if
  // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
  var pn = remain[0]
  var negate = !!this.minimatch.negate
  var rawGlob = pn._glob
  var dotOk = this.dot || rawGlob.charAt(0) === '.'
 
  var matchedEntries = []
  for (var i = 0; i < entries.length; i++) {
    var e = entries[i]
    if (e.charAt(0) !== '.' || dotOk) {
      var m
      if (negate && !prefix) {
        m = !e.match(pn)
      } else {
        m = e.match(pn)
      }
      if (m)
        matchedEntries.push(e)
    }
  }
 
  //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
 
  var len = matchedEntries.length
  // If there are no matched entries, then nothing matches.
  if (len === 0)
    return cb()
 
  // if this is the last remaining pattern bit, then no need for
  // an additional stat *unless* the user has specified mark or
  // stat explicitly.  We know they exist, since readdir returned
  // them.
 
  if (remain.length === 1 && !this.mark && !this.stat) {
    if (!this.matches[index])
      this.matches[index] = Object.create(null)
 
    for (var i = 0; i < len; i ++) {
      var e = matchedEntries[i]
      if (prefix) {
        if (prefix !== '/')
          e = prefix + '/' + e
        else
          e = prefix + e
      }
 
      if (e.charAt(0) === '/' && !this.nomount) {
        e = path.join(this.root, e)
      }
      this._emitMatch(index, e)
    }
    // This was the last one, and no stats were needed
    return cb()
  }
 
  // now test all matched entries as stand-ins for that part
  // of the pattern.
  remain.shift()
  for (var i = 0; i < len; i ++) {
    var e = matchedEntries[i]
    var newPattern
    if (prefix) {
      if (prefix !== '/')
        e = prefix + '/' + e
      else
        e = prefix + e
    }
    this._process([e].concat(remain), index, inGlobStar, cb)
  }
  cb()
}
 
Glob.prototype._emitMatch = function (index, e) {
  if (this.aborted)
    return
 
  if (isIgnored(this, e))
    return
 
  if (this.paused) {
    this._emitQueue.push([index, e])
    return
  }
 
  var abs = isAbsolute(e) ? e : this._makeAbs(e)
 
  if (this.mark)
    e = this._mark(e)
 
  if (this.absolute)
    e = abs
 
  if (this.matches[index][e])
    return
 
  if (this.nodir) {
    var c = this.cache[abs]
    if (c === 'DIR' || Array.isArray(c))
      return
  }
 
  this.matches[index][e] = true
 
  var st = this.statCache[abs]
  if (st)
    this.emit('stat', e, st)
 
  this.emit('match', e)
}
 
Glob.prototype._readdirInGlobStar = function (abs, cb) {
  if (this.aborted)
    return
 
  // follow all symlinked directories forever
  // just proceed as if this is a non-globstar situation
  if (this.follow)
    return this._readdir(abs, false, cb)
 
  var lstatkey = 'lstat\0' + abs
  var self = this
  var lstatcb = inflight(lstatkey, lstatcb_)
 
  if (lstatcb)
    fs.lstat(abs, lstatcb)
 
  function lstatcb_ (er, lstat) {
    if (er && er.code === 'ENOENT')
      return cb()
 
    var isSym = lstat && lstat.isSymbolicLink()
    self.symlinks[abs] = isSym
 
    // If it's not a symlink or a dir, then it's definitely a regular file.
    // don't bother doing a readdir in that case.
    if (!isSym && lstat && !lstat.isDirectory()) {
      self.cache[abs] = 'FILE'
      cb()
    } else
      self._readdir(abs, false, cb)
  }
}
 
Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  if (this.aborted)
    return
 
  cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
  if (!cb)
    return
 
  //console.error('RD %j %j', +inGlobStar, abs)
  if (inGlobStar && !ownProp(this.symlinks, abs))
    return this._readdirInGlobStar(abs, cb)
 
  if (ownProp(this.cache, abs)) {
    var c = this.cache[abs]
    if (!c || c === 'FILE')
      return cb()
 
    if (Array.isArray(c))
      return cb(null, c)
  }
 
  var self = this
  fs.readdir(abs, readdirCb(this, abs, cb))
}
 
function readdirCb (self, abs, cb) {
  return function (er, entries) {
    if (er)
      self._readdirError(abs, er, cb)
    else
      self._readdirEntries(abs, entries, cb)
  }
}
 
Glob.prototype._readdirEntries = function (abs, entries, cb) {
  if (this.aborted)
    return
 
  // if we haven't asked to stat everything, then just
  // assume that everything in there exists, so we can avoid
  // having to stat it a second time.
  if (!this.mark && !this.stat) {
    for (var i = 0; i < entries.length; i ++) {
      var e = entries[i]
      if (abs === '/')
        e = abs + e
      else
        e = abs + '/' + e
      this.cache[e] = true
    }
  }
 
  this.cache[abs] = entries
  return cb(null, entries)
}
 
Glob.prototype._readdirError = function (f, er, cb) {
  if (this.aborted)
    return
 
  // handle errors, and cache the information
  switch (er.code) {
    case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
    case 'ENOTDIR': // totally normal. means it *does* exist.
      var abs = this._makeAbs(f)
      this.cache[abs] = 'FILE'
      if (abs === this.cwdAbs) {
        var error = new Error(er.code + ' invalid cwd ' + this.cwd)
        error.path = this.cwd
        error.code = er.code
        this.emit('error', error)
        this.abort()
      }
      break
 
    case 'ENOENT': // not terribly unusual
    case 'ELOOP':
    case 'ENAMETOOLONG':
    case 'UNKNOWN':
      this.cache[this._makeAbs(f)] = false
      break
 
    default: // some unusual error.  Treat as failure.
      this.cache[this._makeAbs(f)] = false
      if (this.strict) {
        this.emit('error', er)
        // If the error is handled, then we abort
        // if not, we threw out of here
        this.abort()
      }
      if (!this.silent)
        console.error('glob error', er)
      break
  }
 
  return cb()
}
 
Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  var self = this
  this._readdir(abs, inGlobStar, function (er, entries) {
    self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  })
}
 
 
Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  //console.error('pgs2', prefix, remain[0], entries)
 
  // no entries means not a dir, so it can never have matches
  // foo.txt/** doesn't match foo.txt
  if (!entries)
    return cb()
 
  // test without the globstar, and with every child both below
  // and replacing the globstar.
  var remainWithoutGlobStar = remain.slice(1)
  var gspref = prefix ? [ prefix ] : []
  var noGlobStar = gspref.concat(remainWithoutGlobStar)
 
  // the noGlobStar pattern exits the inGlobStar state
  this._process(noGlobStar, index, false, cb)
 
  var isSym = this.symlinks[abs]
  var len = entries.length
 
  // If it's a symlink, and we're in a globstar, then stop
  if (isSym && inGlobStar)
    return cb()
 
  for (var i = 0; i < len; i++) {
    var e = entries[i]
    if (e.charAt(0) === '.' && !this.dot)
      continue
 
    // these two cases enter the inGlobStar state
    var instead = gspref.concat(entries[i], remainWithoutGlobStar)
    this._process(instead, index, true, cb)
 
    var below = gspref.concat(entries[i], remain)
    this._process(below, index, true, cb)
  }
 
  cb()
}
 
Glob.prototype._processSimple = function (prefix, index, cb) {
  // XXX review this.  Shouldn't it be doing the mounting etc
  // before doing stat?  kinda weird?
  var self = this
  this._stat(prefix, function (er, exists) {
    self._processSimple2(prefix, index, er, exists, cb)
  })
}
Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
 
  //console.error('ps2', prefix, exists)
 
  if (!this.matches[index])
    this.matches[index] = Object.create(null)
 
  // If it doesn't exist, then just mark the lack of results
  if (!exists)
    return cb()
 
  if (prefix && isAbsolute(prefix) && !this.nomount) {
    var trail = /[\/\\]$/.test(prefix)
    if (prefix.charAt(0) === '/') {
      prefix = path.join(this.root, prefix)
    } else {
      prefix = path.resolve(this.root, prefix)
      if (trail)
        prefix += '/'
    }
  }
 
  if (process.platform === 'win32')
    prefix = prefix.replace(/\\/g, '/')
 
  // Mark this as a match
  this._emitMatch(index, prefix)
  cb()
}
 
// Returns either 'DIR', 'FILE', or false
Glob.prototype._stat = function (f, cb) {
  var abs = this._makeAbs(f)
  var needDir = f.slice(-1) === '/'
 
  if (f.length > this.maxLength)
    return cb()
 
  if (!this.stat && ownProp(this.cache, abs)) {
    var c = this.cache[abs]
 
    if (Array.isArray(c))
      c = 'DIR'
 
    // It exists, but maybe not how we need it
    if (!needDir || c === 'DIR')
      return cb(null, c)
 
    if (needDir && c === 'FILE')
      return cb()
 
    // otherwise we have to stat, because maybe c=true
    // if we know it exists, but not what it is.
  }
 
  var exists
  var stat = this.statCache[abs]
  if (stat !== undefined) {
    if (stat === false)
      return cb(null, stat)
    else {
      var type = stat.isDirectory() ? 'DIR' : 'FILE'
      if (needDir && type === 'FILE')
        return cb()
      else
        return cb(null, type, stat)
    }
  }
 
  var self = this
  var statcb = inflight('stat\0' + abs, lstatcb_)
  if (statcb)
    fs.lstat(abs, statcb)
 
  function lstatcb_ (er, lstat) {
    if (lstat && lstat.isSymbolicLink()) {
      // If it's a symlink, then treat it as the target, unless
      // the target does not exist, then treat it as a file.
      return fs.stat(abs, function (er, stat) {
        if (er)
          self._stat2(f, abs, null, lstat, cb)
        else
          self._stat2(f, abs, er, stat, cb)
      })
    } else {
      self._stat2(f, abs, er, lstat, cb)
    }
  }
}
 
Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
    this.statCache[abs] = false
    return cb()
  }
 
  var needDir = f.slice(-1) === '/'
  this.statCache[abs] = stat
 
  if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
    return cb(null, false, stat)
 
  var c = true
  if (stat)
    c = stat.isDirectory() ? 'DIR' : 'FILE'
  this.cache[abs] = this.cache[abs] || c
 
  if (needDir && c === 'FILE')
    return cb()
 
  return cb(null, c, stat)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/sync.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/sync.js

Statements: 12.09% (33 / 273)      Branches: 0% (0 / 190)      Functions: 0% (0 / 16)      Lines: 12.09% (33 / 273)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 4881 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1               1                                               1                                               1                                                                                                                     1                                                                                                                                                       1                                                         1                                                             1                                             1                                         1                                                               1                                                                             1                                                             1                                                                                                                           1       1        
module.exports = globSync
globSync.GlobSync = GlobSync
 
var fs = require('fs')
var rp = require('fs.realpath')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var Glob = require('./glob.js').Glob
var util = require('util')
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var common = require('./common.js')
var alphasort = common.alphasort
var alphasorti = common.alphasorti
var setopts = common.setopts
var ownProp = common.ownProp
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
 
function globSync (pattern, options) {
  if (typeof options === 'function' || arguments.length === 3)
    throw new TypeError('callback provided to sync glob\n'+
                        'See: https://github.com/isaacs/node-glob/issues/167')
 
  return new GlobSync(pattern, options).found
}
 
function GlobSync (pattern, options) {
  if (!pattern)
    throw new Error('must provide pattern')
 
  if (typeof options === 'function' || arguments.length === 3)
    throw new TypeError('callback provided to sync glob\n'+
                        'See: https://github.com/isaacs/node-glob/issues/167')
 
  if (!(this instanceof GlobSync))
    return new GlobSync(pattern, options)
 
  setopts(this, pattern, options)
 
  if (this.noprocess)
    return this
 
  var n = this.minimatch.set.length
  this.matches = new Array(n)
  for (var i = 0; i < n; i ++) {
    this._process(this.minimatch.set[i], i, false)
  }
  this._finish()
}
 
GlobSync.prototype._finish = function () {
  assert(this instanceof GlobSync)
  if (this.realpath) {
    var self = this
    this.matches.forEach(function (matchset, index) {
      var set = self.matches[index] = Object.create(null)
      for (var p in matchset) {
        try {
          p = self._makeAbs(p)
          var real = rp.realpathSync(p, self.realpathCache)
          set[real] = true
        } catch (er) {
          if (er.syscall === 'stat')
            set[self._makeAbs(p)] = true
          else
            throw er
        }
      }
    })
  }
  common.finish(this)
}
 
 
GlobSync.prototype._process = function (pattern, index, inGlobStar) {
  assert(this instanceof GlobSync)
 
  // Get the first [n] parts of pattern that are all strings.
  var n = 0
  while (typeof pattern[n] === 'string') {
    n ++
  }
  // now n is the index of the first one that is *not* a string.
 
  // See if there's anything else
  var prefix
  switch (n) {
    // if not, then this is rather simple
    case pattern.length:
      this._processSimple(pattern.join('/'), index)
      return
 
    case 0:
      // pattern *starts* with some non-trivial item.
      // going to readdir(cwd), but not include the prefix in matches.
      prefix = null
      break
 
    default:
      // pattern has some string bits in the front.
      // whatever it starts with, whether that's 'absolute' like /foo/bar,
      // or 'relative' like '../baz'
      prefix = pattern.slice(0, n).join('/')
      break
  }
 
  var remain = pattern.slice(n)
 
  // get the list of entries.
  var read
  if (prefix === null)
    read = '.'
  else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
    if (!prefix || !isAbsolute(prefix))
      prefix = '/' + prefix
    read = prefix
  } else
    read = prefix
 
  var abs = this._makeAbs(read)
 
  //if ignored, skip processing
  if (childrenIgnored(this, read))
    return
 
  var isGlobStar = remain[0] === minimatch.GLOBSTAR
  if (isGlobStar)
    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
  else
    this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
}
 
 
GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  var entries = this._readdir(abs, inGlobStar)
 
  // if the abs isn't a dir, then nothing can match!
  if (!entries)
    return
 
  // It will only match dot entries if it starts with a dot, or if
  // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
  var pn = remain[0]
  var negate = !!this.minimatch.negate
  var rawGlob = pn._glob
  var dotOk = this.dot || rawGlob.charAt(0) === '.'
 
  var matchedEntries = []
  for (var i = 0; i < entries.length; i++) {
    var e = entries[i]
    if (e.charAt(0) !== '.' || dotOk) {
      var m
      if (negate && !prefix) {
        m = !e.match(pn)
      } else {
        m = e.match(pn)
      }
      if (m)
        matchedEntries.push(e)
    }
  }
 
  var len = matchedEntries.length
  // If there are no matched entries, then nothing matches.
  if (len === 0)
    return
 
  // if this is the last remaining pattern bit, then no need for
  // an additional stat *unless* the user has specified mark or
  // stat explicitly.  We know they exist, since readdir returned
  // them.
 
  if (remain.length === 1 && !this.mark && !this.stat) {
    if (!this.matches[index])
      this.matches[index] = Object.create(null)
 
    for (var i = 0; i < len; i ++) {
      var e = matchedEntries[i]
      if (prefix) {
        if (prefix.slice(-1) !== '/')
          e = prefix + '/' + e
        else
          e = prefix + e
      }
 
      if (e.charAt(0) === '/' && !this.nomount) {
        e = path.join(this.root, e)
      }
      this._emitMatch(index, e)
    }
    // This was the last one, and no stats were needed
    return
  }
 
  // now test all matched entries as stand-ins for that part
  // of the pattern.
  remain.shift()
  for (var i = 0; i < len; i ++) {
    var e = matchedEntries[i]
    var newPattern
    if (prefix)
      newPattern = [prefix, e]
    else
      newPattern = [e]
    this._process(newPattern.concat(remain), index, inGlobStar)
  }
}
 
 
GlobSync.prototype._emitMatch = function (index, e) {
  if (isIgnored(this, e))
    return
 
  var abs = this._makeAbs(e)
 
  if (this.mark)
    e = this._mark(e)
 
  if (this.absolute) {
    e = abs
  }
 
  if (this.matches[index][e])
    return
 
  if (this.nodir) {
    var c = this.cache[abs]
    if (c === 'DIR' || Array.isArray(c))
      return
  }
 
  this.matches[index][e] = true
 
  if (this.stat)
    this._stat(e)
}
 
 
GlobSync.prototype._readdirInGlobStar = function (abs) {
  // follow all symlinked directories forever
  // just proceed as if this is a non-globstar situation
  if (this.follow)
    return this._readdir(abs, false)
 
  var entries
  var lstat
  var stat
  try {
    lstat = fs.lstatSync(abs)
  } catch (er) {
    if (er.code === 'ENOENT') {
      // lstat failed, doesn't exist
      return null
    }
  }
 
  var isSym = lstat && lstat.isSymbolicLink()
  this.symlinks[abs] = isSym
 
  // If it's not a symlink or a dir, then it's definitely a regular file.
  // don't bother doing a readdir in that case.
  if (!isSym && lstat && !lstat.isDirectory())
    this.cache[abs] = 'FILE'
  else
    entries = this._readdir(abs, false)
 
  return entries
}
 
GlobSync.prototype._readdir = function (abs, inGlobStar) {
  var entries
 
  if (inGlobStar && !ownProp(this.symlinks, abs))
    return this._readdirInGlobStar(abs)
 
  if (ownProp(this.cache, abs)) {
    var c = this.cache[abs]
    if (!c || c === 'FILE')
      return null
 
    if (Array.isArray(c))
      return c
  }
 
  try {
    return this._readdirEntries(abs, fs.readdirSync(abs))
  } catch (er) {
    this._readdirError(abs, er)
    return null
  }
}
 
GlobSync.prototype._readdirEntries = function (abs, entries) {
  // if we haven't asked to stat everything, then just
  // assume that everything in there exists, so we can avoid
  // having to stat it a second time.
  if (!this.mark && !this.stat) {
    for (var i = 0; i < entries.length; i ++) {
      var e = entries[i]
      if (abs === '/')
        e = abs + e
      else
        e = abs + '/' + e
      this.cache[e] = true
    }
  }
 
  this.cache[abs] = entries
 
  // mark and cache dir-ness
  return entries
}
 
GlobSync.prototype._readdirError = function (f, er) {
  // handle errors, and cache the information
  switch (er.code) {
    case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
    case 'ENOTDIR': // totally normal. means it *does* exist.
      var abs = this._makeAbs(f)
      this.cache[abs] = 'FILE'
      if (abs === this.cwdAbs) {
        var error = new Error(er.code + ' invalid cwd ' + this.cwd)
        error.path = this.cwd
        error.code = er.code
        throw error
      }
      break
 
    case 'ENOENT': // not terribly unusual
    case 'ELOOP':
    case 'ENAMETOOLONG':
    case 'UNKNOWN':
      this.cache[this._makeAbs(f)] = false
      break
 
    default: // some unusual error.  Treat as failure.
      this.cache[this._makeAbs(f)] = false
      if (this.strict)
        throw er
      if (!this.silent)
        console.error('glob error', er)
      break
  }
}
 
GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
 
  var entries = this._readdir(abs, inGlobStar)
 
  // no entries means not a dir, so it can never have matches
  // foo.txt/** doesn't match foo.txt
  if (!entries)
    return
 
  // test without the globstar, and with every child both below
  // and replacing the globstar.
  var remainWithoutGlobStar = remain.slice(1)
  var gspref = prefix ? [ prefix ] : []
  var noGlobStar = gspref.concat(remainWithoutGlobStar)
 
  // the noGlobStar pattern exits the inGlobStar state
  this._process(noGlobStar, index, false)
 
  var len = entries.length
  var isSym = this.symlinks[abs]
 
  // If it's a symlink, and we're in a globstar, then stop
  if (isSym && inGlobStar)
    return
 
  for (var i = 0; i < len; i++) {
    var e = entries[i]
    if (e.charAt(0) === '.' && !this.dot)
      continue
 
    // these two cases enter the inGlobStar state
    var instead = gspref.concat(entries[i], remainWithoutGlobStar)
    this._process(instead, index, true)
 
    var below = gspref.concat(entries[i], remain)
    this._process(below, index, true)
  }
}
 
GlobSync.prototype._processSimple = function (prefix, index) {
  // XXX review this.  Shouldn't it be doing the mounting etc
  // before doing stat?  kinda weird?
  var exists = this._stat(prefix)
 
  if (!this.matches[index])
    this.matches[index] = Object.create(null)
 
  // If it doesn't exist, then just mark the lack of results
  if (!exists)
    return
 
  if (prefix && isAbsolute(prefix) && !this.nomount) {
    var trail = /[\/\\]$/.test(prefix)
    if (prefix.charAt(0) === '/') {
      prefix = path.join(this.root, prefix)
    } else {
      prefix = path.resolve(this.root, prefix)
      if (trail)
        prefix += '/'
    }
  }
 
  if (process.platform === 'win32')
    prefix = prefix.replace(/\\/g, '/')
 
  // Mark this as a match
  this._emitMatch(index, prefix)
}
 
// Returns either 'DIR', 'FILE', or false
GlobSync.prototype._stat = function (f) {
  var abs = this._makeAbs(f)
  var needDir = f.slice(-1) === '/'
 
  if (f.length > this.maxLength)
    return false
 
  if (!this.stat && ownProp(this.cache, abs)) {
    var c = this.cache[abs]
 
    if (Array.isArray(c))
      c = 'DIR'
 
    // It exists, but maybe not how we need it
    if (!needDir || c === 'DIR')
      return c
 
    if (needDir && c === 'FILE')
      return false
 
    // otherwise we have to stat, because maybe c=true
    // if we know it exists, but not what it is.
  }
 
  var exists
  var stat = this.statCache[abs]
  if (!stat) {
    var lstat
    try {
      lstat = fs.lstatSync(abs)
    } catch (er) {
      if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
        this.statCache[abs] = false
        return false
      }
    }
 
    if (lstat && lstat.isSymbolicLink()) {
      try {
        stat = fs.statSync(abs)
      } catch (er) {
        stat = lstat
      }
    } else {
      stat = lstat
    }
  }
 
  this.statCache[abs] = stat
 
  var c = true
  if (stat)
    c = stat.isDirectory() ? 'DIR' : 'FILE'
 
  this.cache[abs] = this.cache[abs] || c
 
  if (needDir && c === 'FILE')
    return false
 
  return c
}
 
GlobSync.prototype._mark = function (p) {
  return common.mark(this, p)
}
 
GlobSync.prototype._makeAbs = function (f) {
  return common.makeAbs(this, f)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/

Statements: 19.19% (38 / 198)      Branches: 2.65% (3 / 113)      Functions: 0% (0 / 21)      Lines: 20.43% (38 / 186)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/
File Statements Branches Functions Lines
index.js 44.74% (17 / 38) 0% (0 / 15) 0% (0 / 6) 44.74% (17 / 38)
old.js 13.13% (21 / 160) 3.06% (3 / 98) 0% (0 / 15) 14.19% (21 / 148)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/index.js

Statements: 44.74% (17 / 38)      Branches: 0% (0 / 15)      Functions: 0% (0 / 6)      Lines: 44.74% (17 / 38)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 681 1 1 1 1 1   1 1 1   1 1 1   1               1                                   1                               1         1          
module.exports = realpath
realpath.realpath = realpath
realpath.sync = realpathSync
realpath.realpathSync = realpathSync
realpath.monkeypatch = monkeypatch
realpath.unmonkeypatch = unmonkeypatch
 
var fs = require('fs')
var origRealpath = fs.realpath
var origRealpathSync = fs.realpathSync
 
var version = process.version
var ok = /^v[0-5]\./.test(version)
var old = require('./old.js')
 
function newError (er) {
  return er && er.syscall === 'realpath' && (
    er.code === 'ELOOP' ||
    er.code === 'ENOMEM' ||
    er.code === 'ENAMETOOLONG'
  )
}
 
function realpath (p, cache, cb) {
  if (ok) {
    return origRealpath(p, cache, cb)
  }
 
  if (typeof cache === 'function') {
    cb = cache
    cache = null
  }
  origRealpath(p, cache, function (er, result) {
    if (newError(er)) {
      old.realpath(p, cache, cb)
    } else {
      cb(er, result)
    }
  })
}
 
function realpathSync (p, cache) {
  if (ok) {
    return origRealpathSync(p, cache)
  }
 
  try {
    return origRealpathSync(p, cache)
  } catch (er) {
    if (newError(er)) {
      return old.realpathSync(p, cache)
    } else {
      throw er
    }
  }
}
 
function monkeypatch () {
  fs.realpath = realpath
  fs.realpathSync = realpathSync
}
 
function unmonkeypatch () {
  fs.realpath = origRealpath
  fs.realpathSync = origRealpathSync
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/old.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/fs.realpath/old.js

Statements: 13.13% (21 / 160)      Branches: 3.06% (3 / 98)      Functions: 0% (0 / 15)      Lines: 14.19% (21 / 148)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305                                          1 1 1       1   1                       1               1                             1       1       1     1       1     1     1                                             1                                                                                                                                                   1                                                       1                                           1                                                       1                                                         1               1              
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
var pathModule = require('path');
var isWindows = process.platform === 'win32';
var fs = require('fs');
 
// JavaScript implementation of realpath, ported from node pre-v6
 
var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
 
function rethrow() {
  // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  // is fairly slow to generate.
  var callback;
  if (DEBUG) {
    var backtrace = new Error;
    callback = debugCallback;
  } else
    callback = missingCallback;
 
  return callback;
 
  function debugCallback(err) {
    if (err) {
      backtrace.message = err.message;
      err = backtrace;
      missingCallback(err);
    }
  }
 
  function missingCallback(err) {
    if (err) {
      if (process.throwDeprecation)
        throw err;  // Forgot a callback but don't know where? Use NODE_DEBUG=fs
      else if (!process.noDeprecation) {
        var msg = 'fs: missing callback ' + (err.stack || err.message);
        if (process.traceDeprecation)
          console.trace(msg);
        else
          console.error(msg);
      }
    }
  }
}
 
function maybeCallback(cb) {
  return typeof cb === 'function' ? cb : rethrow();
}
 
var normalize = pathModule.normalize;
 
// Regexp that finds the next partion of a (partial) path
// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
Iif (isWindows) {
  var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
} else {
  var nextPartRe = /(.*?)(?:[\/]+|$)/g;
}
 
// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
Iif (isWindows) {
  var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
} else {
  var splitRootRe = /^[\/]*/;
}
 
exports.realpathSync = function realpathSync(p, cache) {
  // make p is absolute
  p = pathModule.resolve(p);
 
  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
    return cache[p];
  }
 
  var original = p,
      seenLinks = {},
      knownHard = {};
 
  // current character position in p
  var pos;
  // the partial path so far, including a trailing slash if any
  var current;
  // the partial path without a trailing slash (except when pointing at a root)
  var base;
  // the partial path scanned in the previous round, with slash
  var previous;
 
  start();
 
  function start() {
    // Skip over roots
    var m = splitRootRe.exec(p);
    pos = m[0].length;
    current = m[0];
    base = m[0];
    previous = '';
 
    // On windows, check that the root exists. On unix there is no need.
    if (isWindows && !knownHard[base]) {
      fs.lstatSync(base);
      knownHard[base] = true;
    }
  }
 
  // walk down the path, swapping out linked pathparts for their real
  // values
  // NB: p.length changes.
  while (pos < p.length) {
    // find the next part
    nextPartRe.lastIndex = pos;
    var result = nextPartRe.exec(p);
    previous = current;
    current += result[0];
    base = previous + result[1];
    pos = nextPartRe.lastIndex;
 
    // continue if not a symlink
    if (knownHard[base] || (cache && cache[base] === base)) {
      continue;
    }
 
    var resolvedLink;
    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
      // some known symbolic link.  no need to stat again.
      resolvedLink = cache[base];
    } else {
      var stat = fs.lstatSync(base);
      if (!stat.isSymbolicLink()) {
        knownHard[base] = true;
        if (cache) cache[base] = base;
        continue;
      }
 
      // read the link if it wasn't read before
      // dev/ino always return 0 on windows, so skip the check.
      var linkTarget = null;
      if (!isWindows) {
        var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
        if (seenLinks.hasOwnProperty(id)) {
          linkTarget = seenLinks[id];
        }
      }
      if (linkTarget === null) {
        fs.statSync(base);
        linkTarget = fs.readlinkSync(base);
      }
      resolvedLink = pathModule.resolve(previous, linkTarget);
      // track this, if given a cache.
      if (cache) cache[base] = resolvedLink;
      if (!isWindows) seenLinks[id] = linkTarget;
    }
 
    // resolve the link, then start over
    p = pathModule.resolve(resolvedLink, p.slice(pos));
    start();
  }
 
  if (cache) cache[original] = p;
 
  return p;
};
 
 
exports.realpath = function realpath(p, cache, cb) {
  if (typeof cb !== 'function') {
    cb = maybeCallback(cache);
    cache = null;
  }
 
  // make p is absolute
  p = pathModule.resolve(p);
 
  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
    return process.nextTick(cb.bind(null, null, cache[p]));
  }
 
  var original = p,
      seenLinks = {},
      knownHard = {};
 
  // current character position in p
  var pos;
  // the partial path so far, including a trailing slash if any
  var current;
  // the partial path without a trailing slash (except when pointing at a root)
  var base;
  // the partial path scanned in the previous round, with slash
  var previous;
 
  start();
 
  function start() {
    // Skip over roots
    var m = splitRootRe.exec(p);
    pos = m[0].length;
    current = m[0];
    base = m[0];
    previous = '';
 
    // On windows, check that the root exists. On unix there is no need.
    if (isWindows && !knownHard[base]) {
      fs.lstat(base, function(err) {
        if (err) return cb(err);
        knownHard[base] = true;
        LOOP();
      });
    } else {
      process.nextTick(LOOP);
    }
  }
 
  // walk down the path, swapping out linked pathparts for their real
  // values
  function LOOP() {
    // stop if scanned past end of path
    if (pos >= p.length) {
      if (cache) cache[original] = p;
      return cb(null, p);
    }
 
    // find the next part
    nextPartRe.lastIndex = pos;
    var result = nextPartRe.exec(p);
    previous = current;
    current += result[0];
    base = previous + result[1];
    pos = nextPartRe.lastIndex;
 
    // continue if not a symlink
    if (knownHard[base] || (cache && cache[base] === base)) {
      return process.nextTick(LOOP);
    }
 
    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
      // known symbolic link.  no need to stat again.
      return gotResolvedLink(cache[base]);
    }
 
    return fs.lstat(base, gotStat);
  }
 
  function gotStat(err, stat) {
    if (err) return cb(err);
 
    // if not a symlink, skip to the next path part
    if (!stat.isSymbolicLink()) {
      knownHard[base] = true;
      if (cache) cache[base] = base;
      return process.nextTick(LOOP);
    }
 
    // stat & read the link if not read before
    // call gotTarget as soon as the link target is known
    // dev/ino always return 0 on windows, so skip the check.
    if (!isWindows) {
      var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
      if (seenLinks.hasOwnProperty(id)) {
        return gotTarget(null, seenLinks[id], base);
      }
    }
    fs.stat(base, function(err) {
      if (err) return cb(err);
 
      fs.readlink(base, function(err, target) {
        if (!isWindows) seenLinks[id] = target;
        gotTarget(err, target);
      });
    });
  }
 
  function gotTarget(err, target, base) {
    if (err) return cb(err);
 
    var resolvedLink = pathModule.resolve(previous, target);
    if (cache) cache[base] = resolvedLink;
    gotResolvedLink(resolvedLink);
  }
 
  function gotResolvedLink(resolvedLink) {
    // resolve the link, then start over
    p = pathModule.resolve(resolvedLink, p.slice(pos));
    start();
  }
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/

Statements: 10.77% (46 / 427)      Branches: 0% (0 / 260)      Functions: 5.88% (2 / 34)      Lines: 11.41% (46 / 403)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/
File Statements Branches Functions Lines
minimatch.js 10.77% (46 / 427) 0% (0 / 260) 5.88% (2 / 34) 11.41% (46 / 403)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/minimatch.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/minimatch.js

Statements: 10.77% (46 / 427)      Branches: 0% (0 / 260)      Functions: 5.88% (2 / 34)      Lines: 11.41% (46 / 403)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 9251 1   1 1 1     1 1   1                   1     1         1       1     1     1 1 14 14         1   1 1             1                         1                               1         1                                   1                                                         1   1 1                                                                                                             1 1                                                         1       1   1                                                                       1 1 1                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1       1 1                                                                                         1                       1 1                                                                                                                       1                                                                                                                                                                                                                                                                                                                         1       1        
module.exports = minimatch
minimatch.Minimatch = Minimatch
 
var path = { sep: '/' }
try {
  path = require('path')
} catch (er) {}
 
var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
var expand = require('brace-expansion')
 
var plTypes = {
  '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  '?': { open: '(?:', close: ')?' },
  '+': { open: '(?:', close: ')+' },
  '*': { open: '(?:', close: ')*' },
  '@': { open: '(?:', close: ')' }
}
 
// any single thing other than /
// don't need to escape / when using new RegExp()
var qmark = '[^/]'
 
// * => any number of characters
var star = qmark + '*?'
 
// ** when dots are allowed.  Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
 
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
 
// characters that need to be escaped in RegExp.
var reSpecials = charSet('().*{}+?[]^$\\!')
 
// "abc" -> { a:true, b:true, c:true }
function charSet (s) {
  return s.split('').reduce(function (set, c) {
    set[c] = true
    return set
  }, {})
}
 
// normalizes slashes.
var slashSplit = /\/+/
 
minimatch.filter = filter
function filter (pattern, options) {
  options = options || {}
  return function (p, i, list) {
    return minimatch(p, pattern, options)
  }
}
 
function ext (a, b) {
  a = a || {}
  b = b || {}
  var t = {}
  Object.keys(b).forEach(function (k) {
    t[k] = b[k]
  })
  Object.keys(a).forEach(function (k) {
    t[k] = a[k]
  })
  return t
}
 
minimatch.defaults = function (def) {
  if (!def || !Object.keys(def).length) return minimatch
 
  var orig = minimatch
 
  var m = function minimatch (p, pattern, options) {
    return orig.minimatch(p, pattern, ext(def, options))
  }
 
  m.Minimatch = function Minimatch (pattern, options) {
    return new orig.Minimatch(pattern, ext(def, options))
  }
 
  return m
}
 
Minimatch.defaults = function (def) {
  if (!def || !Object.keys(def).length) return Minimatch
  return minimatch.defaults(def).Minimatch
}
 
function minimatch (p, pattern, options) {
  if (typeof pattern !== 'string') {
    throw new TypeError('glob pattern string required')
  }
 
  if (!options) options = {}
 
  // shortcut: comments match nothing.
  if (!options.nocomment && pattern.charAt(0) === '#') {
    return false
  }
 
  // "" only matches ""
  if (pattern.trim() === '') return p === ''
 
  return new Minimatch(pattern, options).match(p)
}
 
function Minimatch (pattern, options) {
  if (!(this instanceof Minimatch)) {
    return new Minimatch(pattern, options)
  }
 
  if (typeof pattern !== 'string') {
    throw new TypeError('glob pattern string required')
  }
 
  if (!options) options = {}
  pattern = pattern.trim()
 
  // windows support: need to use /, not \
  if (path.sep !== '/') {
    pattern = pattern.split(path.sep).join('/')
  }
 
  this.options = options
  this.set = []
  this.pattern = pattern
  this.regexp = null
  this.negate = false
  this.comment = false
  this.empty = false
 
  // make the set of regexps etc.
  this.make()
}
 
Minimatch.prototype.debug = function () {}
 
Minimatch.prototype.make = make
function make () {
  // don't do it more than once.
  if (this._made) return
 
  var pattern = this.pattern
  var options = this.options
 
  // empty patterns and comments match nothing.
  if (!options.nocomment && pattern.charAt(0) === '#') {
    this.comment = true
    return
  }
  if (!pattern) {
    this.empty = true
    return
  }
 
  // step 1: figure out negation, etc.
  this.parseNegate()
 
  // step 2: expand braces
  var set = this.globSet = this.braceExpand()
 
  if (options.debug) this.debug = console.error
 
  this.debug(this.pattern, set)
 
  // step 3: now we have a set, so turn each one into a series of path-portion
  // matching patterns.
  // These will be regexps, except in the case of "**", which is
  // set to the GLOBSTAR object for globstar behavior,
  // and will not contain any / characters
  set = this.globParts = set.map(function (s) {
    return s.split(slashSplit)
  })
 
  this.debug(this.pattern, set)
 
  // glob --> regexps
  set = set.map(function (s, si, set) {
    return s.map(this.parse, this)
  }, this)
 
  this.debug(this.pattern, set)
 
  // filter out everything that didn't compile properly.
  set = set.filter(function (s) {
    return s.indexOf(false) === -1
  })
 
  this.debug(this.pattern, set)
 
  this.set = set
}
 
Minimatch.prototype.parseNegate = parseNegate
function parseNegate () {
  var pattern = this.pattern
  var negate = false
  var options = this.options
  var negateOffset = 0
 
  if (options.nonegate) return
 
  for (var i = 0, l = pattern.length
    ; i < l && pattern.charAt(i) === '!'
    ; i++) {
    negate = !negate
    negateOffset++
  }
 
  if (negateOffset) this.pattern = pattern.substr(negateOffset)
  this.negate = negate
}
 
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = function (pattern, options) {
  return braceExpand(pattern, options)
}
 
Minimatch.prototype.braceExpand = braceExpand
 
function braceExpand (pattern, options) {
  if (!options) {
    if (this instanceof Minimatch) {
      options = this.options
    } else {
      options = {}
    }
  }
 
  pattern = typeof pattern === 'undefined'
    ? this.pattern : pattern
 
  if (typeof pattern === 'undefined') {
    throw new TypeError('undefined pattern')
  }
 
  if (options.nobrace ||
    !pattern.match(/\{.*\}/)) {
    // shortcut. no need to expand.
    return [pattern]
  }
 
  return expand(pattern)
}
 
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion.  Otherwise, any series
// of * is equivalent to a single *.  Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
Minimatch.prototype.parse = parse
var SUBPARSE = {}
function parse (pattern, isSub) {
  if (pattern.length > 1024 * 64) {
    throw new TypeError('pattern is too long')
  }
 
  var options = this.options
 
  // shortcuts
  if (!options.noglobstar && pattern === '**') return GLOBSTAR
  if (pattern === '') return ''
 
  var re = ''
  var hasMagic = !!options.nocase
  var escaping = false
  // ? => one single character
  var patternListStack = []
  var negativeLists = []
  var stateChar
  var inClass = false
  var reClassStart = -1
  var classStart = -1
  // . and .. never match anything that doesn't start with .,
  // even when options.dot is set.
  var patternStart = pattern.charAt(0) === '.' ? '' // anything
  // not (start or / followed by . or .. followed by / or end)
  : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  : '(?!\\.)'
  var self = this
 
  function clearStateChar () {
    if (stateChar) {
      // we had some state-tracking character
      // that wasn't consumed by this pass.
      switch (stateChar) {
        case '*':
          re += star
          hasMagic = true
        break
        case '?':
          re += qmark
          hasMagic = true
        break
        default:
          re += '\\' + stateChar
        break
      }
      self.debug('clearStateChar %j %j', stateChar, re)
      stateChar = false
    }
  }
 
  for (var i = 0, len = pattern.length, c
    ; (i < len) && (c = pattern.charAt(i))
    ; i++) {
    this.debug('%s\t%s %s %j', pattern, i, re, c)
 
    // skip over any that are escaped.
    if (escaping && reSpecials[c]) {
      re += '\\' + c
      escaping = false
      continue
    }
 
    switch (c) {
      case '/':
        // completely not allowed, even escaped.
        // Should already be path-split by now.
        return false
 
      case '\\':
        clearStateChar()
        escaping = true
      continue
 
      // the various stateChar values
      // for the "extglob" stuff.
      case '?':
      case '*':
      case '+':
      case '@':
      case '!':
        this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
 
        // all of those are literals inside a class, except that
        // the glob [!a] means [^a] in regexp
        if (inClass) {
          this.debug('  in class')
          if (c === '!' && i === classStart + 1) c = '^'
          re += c
          continue
        }
 
        // if we already have a stateChar, then it means
        // that there was something like ** or +? in there.
        // Handle the stateChar, then proceed with this one.
        self.debug('call clearStateChar %j', stateChar)
        clearStateChar()
        stateChar = c
        // if extglob is disabled, then +(asdf|foo) isn't a thing.
        // just clear the statechar *now*, rather than even diving into
        // the patternList stuff.
        if (options.noext) clearStateChar()
      continue
 
      case '(':
        if (inClass) {
          re += '('
          continue
        }
 
        if (!stateChar) {
          re += '\\('
          continue
        }
 
        patternListStack.push({
          type: stateChar,
          start: i - 1,
          reStart: re.length,
          open: plTypes[stateChar].open,
          close: plTypes[stateChar].close
        })
        // negation is (?:(?!js)[^/]*)
        re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
        this.debug('plType %j %j', stateChar, re)
        stateChar = false
      continue
 
      case ')':
        if (inClass || !patternListStack.length) {
          re += '\\)'
          continue
        }
 
        clearStateChar()
        hasMagic = true
        var pl = patternListStack.pop()
        // negation is (?:(?!js)[^/]*)
        // The others are (?:<pattern>)<type>
        re += pl.close
        if (pl.type === '!') {
          negativeLists.push(pl)
        }
        pl.reEnd = re.length
      continue
 
      case '|':
        if (inClass || !patternListStack.length || escaping) {
          re += '\\|'
          escaping = false
          continue
        }
 
        clearStateChar()
        re += '|'
      continue
 
      // these are mostly the same in regexp and glob
      case '[':
        // swallow any state-tracking char before the [
        clearStateChar()
 
        if (inClass) {
          re += '\\' + c
          continue
        }
 
        inClass = true
        classStart = i
        reClassStart = re.length
        re += c
      continue
 
      case ']':
        //  a right bracket shall lose its special
        //  meaning and represent itself in
        //  a bracket expression if it occurs
        //  first in the list.  -- POSIX.2 2.8.3.2
        if (i === classStart + 1 || !inClass) {
          re += '\\' + c
          escaping = false
          continue
        }
 
        // handle the case where we left a class open.
        // "[z-a]" is valid, equivalent to "\[z-a\]"
        if (inClass) {
          // split where the last [ was, make sure we don't have
          // an invalid re. if so, re-walk the contents of the
          // would-be class to re-translate any characters that
          // were passed through as-is
          // TODO: It would probably be faster to determine this
          // without a try/catch and a new RegExp, but it's tricky
          // to do safely.  For now, this is safe and works.
          var cs = pattern.substring(classStart + 1, i)
          try {
            RegExp('[' + cs + ']')
          } catch (er) {
            // not a valid class!
            var sp = this.parse(cs, SUBPARSE)
            re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
            hasMagic = hasMagic || sp[1]
            inClass = false
            continue
          }
        }
 
        // finish up the class.
        hasMagic = true
        inClass = false
        re += c
      continue
 
      default:
        // swallow any state char that wasn't consumed
        clearStateChar()
 
        if (escaping) {
          // no need
          escaping = false
        } else if (reSpecials[c]
          && !(c === '^' && inClass)) {
          re += '\\'
        }
 
        re += c
 
    } // switch
  } // for
 
  // handle the case where we left a class open.
  // "[abc" is valid, equivalent to "\[abc"
  if (inClass) {
    // split where the last [ was, and escape it
    // this is a huge pita.  We now have to re-walk
    // the contents of the would-be class to re-translate
    // any characters that were passed through as-is
    cs = pattern.substr(classStart + 1)
    sp = this.parse(cs, SUBPARSE)
    re = re.substr(0, reClassStart) + '\\[' + sp[0]
    hasMagic = hasMagic || sp[1]
  }
 
  // handle the case where we had a +( thing at the *end*
  // of the pattern.
  // each pattern list stack adds 3 chars, and we need to go through
  // and escape any | chars that were passed through as-is for the regexp.
  // Go through and escape them, taking care not to double-escape any
  // | chars that were already escaped.
  for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
    var tail = re.slice(pl.reStart + pl.open.length)
    this.debug('setting tail', re, pl)
    // maybe some even number of \, then maybe 1 \, followed by a |
    tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
      if (!$2) {
        // the | isn't already escaped, so escape it.
        $2 = '\\'
      }
 
      // need to escape all those slashes *again*, without escaping the
      // one that we need for escaping the | character.  As it works out,
      // escaping an even number of slashes can be done by simply repeating
      // it exactly after itself.  That's why this trick works.
      //
      // I am sorry that you have to see this.
      return $1 + $1 + $2 + '|'
    })
 
    this.debug('tail=%j\n   %s', tail, tail, pl, re)
    var t = pl.type === '*' ? star
      : pl.type === '?' ? qmark
      : '\\' + pl.type
 
    hasMagic = true
    re = re.slice(0, pl.reStart) + t + '\\(' + tail
  }
 
  // handle trailing things that only matter at the very end.
  clearStateChar()
  if (escaping) {
    // trailing \\
    re += '\\\\'
  }
 
  // only need to apply the nodot start if the re starts with
  // something that could conceivably capture a dot
  var addPatternStart = false
  switch (re.charAt(0)) {
    case '.':
    case '[':
    case '(': addPatternStart = true
  }
 
  // Hack to work around lack of negative lookbehind in JS
  // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  // like 'a.xyz.yz' doesn't match.  So, the first negative
  // lookahead, has to look ALL the way ahead, to the end of
  // the pattern.
  for (var n = negativeLists.length - 1; n > -1; n--) {
    var nl = negativeLists[n]
 
    var nlBefore = re.slice(0, nl.reStart)
    var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
    var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
    var nlAfter = re.slice(nl.reEnd)
 
    nlLast += nlAfter
 
    // Handle nested stuff like *(*.js|!(*.json)), where open parens
    // mean that we should *not* include the ) in the bit that is considered
    // "after" the negated section.
    var openParensBefore = nlBefore.split('(').length - 1
    var cleanAfter = nlAfter
    for (i = 0; i < openParensBefore; i++) {
      cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
    }
    nlAfter = cleanAfter
 
    var dollar = ''
    if (nlAfter === '' && isSub !== SUBPARSE) {
      dollar = '$'
    }
    var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
    re = newRe
  }
 
  // if the re is not "" at this point, then we need to make sure
  // it doesn't match against an empty path part.
  // Otherwise a/* will match a/, which it should not.
  if (re !== '' && hasMagic) {
    re = '(?=.)' + re
  }
 
  if (addPatternStart) {
    re = patternStart + re
  }
 
  // parsing just a piece of a larger pattern.
  if (isSub === SUBPARSE) {
    return [re, hasMagic]
  }
 
  // skip the regexp for non-magical patterns
  // unescape anything in it, though, so that it'll be
  // an exact match against a file etc.
  if (!hasMagic) {
    return globUnescape(pattern)
  }
 
  var flags = options.nocase ? 'i' : ''
  try {
    var regExp = new RegExp('^' + re + '$', flags)
  } catch (er) {
    // If it was an invalid regular expression, then it can't match
    // anything.  This trick looks for a character after the end of
    // the string, which is of course impossible, except in multi-line
    // mode, but it's not a /m regex.
    return new RegExp('$.')
  }
 
  regExp._glob = pattern
  regExp._src = re
 
  return regExp
}
 
minimatch.makeRe = function (pattern, options) {
  return new Minimatch(pattern, options || {}).makeRe()
}
 
Minimatch.prototype.makeRe = makeRe
function makeRe () {
  if (this.regexp || this.regexp === false) return this.regexp
 
  // at this point, this.set is a 2d array of partial
  // pattern strings, or "**".
  //
  // It's better to use .match().  This function shouldn't
  // be used, really, but it's pretty convenient sometimes,
  // when you just want to work with a regex.
  var set = this.set
 
  if (!set.length) {
    this.regexp = false
    return this.regexp
  }
  var options = this.options
 
  var twoStar = options.noglobstar ? star
    : options.dot ? twoStarDot
    : twoStarNoDot
  var flags = options.nocase ? 'i' : ''
 
  var re = set.map(function (pattern) {
    return pattern.map(function (p) {
      return (p === GLOBSTAR) ? twoStar
      : (typeof p === 'string') ? regExpEscape(p)
      : p._src
    }).join('\\\/')
  }).join('|')
 
  // must match entire pattern
  // ending in a * or ** will make it less strict.
  re = '^(?:' + re + ')$'
 
  // can match anything, as long as it's not this.
  if (this.negate) re = '^(?!' + re + ').*$'
 
  try {
    this.regexp = new RegExp(re, flags)
  } catch (ex) {
    this.regexp = false
  }
  return this.regexp
}
 
minimatch.match = function (list, pattern, options) {
  options = options || {}
  var mm = new Minimatch(pattern, options)
  list = list.filter(function (f) {
    return mm.match(f)
  })
  if (mm.options.nonull && !list.length) {
    list.push(pattern)
  }
  return list
}
 
Minimatch.prototype.match = match
function match (f, partial) {
  this.debug('match', f, this.pattern)
  // short-circuit in the case of busted things.
  // comments, etc.
  if (this.comment) return false
  if (this.empty) return f === ''
 
  if (f === '/' && partial) return true
 
  var options = this.options
 
  // windows: need to use /, not \
  if (path.sep !== '/') {
    f = f.split(path.sep).join('/')
  }
 
  // treat the test path as a set of pathparts.
  f = f.split(slashSplit)
  this.debug(this.pattern, 'split', f)
 
  // just ONE of the pattern sets in this.set needs to match
  // in order for it to be valid.  If negating, then just one
  // match means that we have failed.
  // Either way, return on the first hit.
 
  var set = this.set
  this.debug(this.pattern, 'set', set)
 
  // Find the basename of the path by looking for the last non-empty segment
  var filename
  var i
  for (i = f.length - 1; i >= 0; i--) {
    filename = f[i]
    if (filename) break
  }
 
  for (i = 0; i < set.length; i++) {
    var pattern = set[i]
    var file = f
    if (options.matchBase && pattern.length === 1) {
      file = [filename]
    }
    var hit = this.matchOne(file, pattern, partial)
    if (hit) {
      if (options.flipNegate) return true
      return !this.negate
    }
  }
 
  // didn't get any hits.  this is success if it's a negative
  // pattern, failure otherwise.
  if (options.flipNegate) return false
  return this.negate
}
 
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
Minimatch.prototype.matchOne = function (file, pattern, partial) {
  var options = this.options
 
  this.debug('matchOne',
    { 'this': this, file: file, pattern: pattern })
 
  this.debug('matchOne', file.length, pattern.length)
 
  for (var fi = 0,
      pi = 0,
      fl = file.length,
      pl = pattern.length
      ; (fi < fl) && (pi < pl)
      ; fi++, pi++) {
    this.debug('matchOne loop')
    var p = pattern[pi]
    var f = file[fi]
 
    this.debug(pattern, p, f)
 
    // should be impossible.
    // some invalid regexp stuff in the set.
    if (p === false) return false
 
    if (p === GLOBSTAR) {
      this.debug('GLOBSTAR', [pattern, p, f])
 
      // "**"
      // a/**/b/**/c would match the following:
      // a/b/x/y/z/c
      // a/x/y/z/b/c
      // a/b/x/b/x/c
      // a/b/c
      // To do this, take the rest of the pattern after
      // the **, and see if it would match the file remainder.
      // If so, return success.
      // If not, the ** "swallows" a segment, and try again.
      // This is recursively awful.
      //
      // a/**/b/**/c matching a/b/x/y/z/c
      // - a matches a
      // - doublestar
      //   - matchOne(b/x/y/z/c, b/**/c)
      //     - b matches b
      //     - doublestar
      //       - matchOne(x/y/z/c, c) -> no
      //       - matchOne(y/z/c, c) -> no
      //       - matchOne(z/c, c) -> no
      //       - matchOne(c, c) yes, hit
      var fr = fi
      var pr = pi + 1
      if (pr === pl) {
        this.debug('** at the end')
        // a ** at the end will just swallow the rest.
        // We have found a match.
        // however, it will not swallow /.x, unless
        // options.dot is set.
        // . and .. are *never* matched by **, for explosively
        // exponential reasons.
        for (; fi < fl; fi++) {
          if (file[fi] === '.' || file[fi] === '..' ||
            (!options.dot && file[fi].charAt(0) === '.')) return false
        }
        return true
      }
 
      // ok, let's see if we can swallow whatever we can.
      while (fr < fl) {
        var swallowee = file[fr]
 
        this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
 
        // XXX remove this slice.  Just pass the start index.
        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
          this.debug('globstar found match!', fr, fl, swallowee)
          // found a match.
          return true
        } else {
          // can't swallow "." or ".." ever.
          // can only swallow ".foo" when explicitly asked.
          if (swallowee === '.' || swallowee === '..' ||
            (!options.dot && swallowee.charAt(0) === '.')) {
            this.debug('dot detected!', file, fr, pattern, pr)
            break
          }
 
          // ** swallows a segment, and continue.
          this.debug('globstar swallow a segment, and continue')
          fr++
        }
      }
 
      // no match was found.
      // However, in partial mode, we can't say this is necessarily over.
      // If there's more *pattern* left, then
      if (partial) {
        // ran out of file
        this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
        if (fr === fl) return true
      }
      return false
    }
 
    // something other than **
    // non-magic patterns just have to match exactly
    // patterns with magic have been turned into regexps.
    var hit
    if (typeof p === 'string') {
      if (options.nocase) {
        hit = f.toLowerCase() === p.toLowerCase()
      } else {
        hit = f === p
      }
      this.debug('string match', p, f, hit)
    } else {
      hit = f.match(p)
      this.debug('pattern match', p, f, hit)
    }
 
    if (!hit) return false
  }
 
  // Note: ending in / means that we'll get a final ""
  // at the end of the pattern.  This can only match a
  // corresponding "" at the end of the file.
  // If the file ends in /, then it can only match a
  // a pattern that ends in /, unless the pattern just
  // doesn't have any more for it. But, a/b/ should *not*
  // match "a/b/*", even though "" matches against the
  // [^/]*? pattern, except in partial mode, where it might
  // simply not be reached yet.
  // However, a/b/ should still satisfy a/*
 
  // now either we fell off the end of the pattern, or we're done.
  if (fi === fl && pi === pl) {
    // ran out of pattern and filename at the same time.
    // an exact hit!
    return true
  } else if (fi === fl) {
    // ran out of file, but still had pattern left.
    // this is ok if we're doing the match as part of
    // a glob fs traversal.
    return partial
  } else if (pi === pl) {
    // ran out of pattern, still have file left.
    // this is only acceptable if we're on the very last
    // empty segment of a file with a trailing slash.
    // a/* should match a/b/
    var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
    return emptyFileEnd
  }
 
  // should be unreachable.
  throw new Error('wtf?')
}
 
// replace stuff like \* with *
function globUnescape (s) {
  return s.replace(/\\(.)/g, '$1')
}
 
function regExpEscape (s) {
  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/

Statements: 17.27% (19 / 110)      Branches: 0% (0 / 55)      Functions: 0% (0 / 13)      Lines: 17.59% (19 / 108)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/
File Statements Branches Functions Lines
index.js 17.27% (19 / 110) 0% (0 / 55) 0% (0 / 13) 17.59% (19 / 108)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/index.js

Statements: 17.27% (19 / 110)      Branches: 0% (0 / 55)      Functions: 0% (0 / 13)      Lines: 17.59% (19 / 108)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 2031 1   1   1 1 1 1 1   1           1               1                       1                                                     1                                 1       1     1       1     1       1                                                                                                                                                                                                              
var concatMap = require('concat-map');
var balanced = require('balanced-match');
 
module.exports = expandTop;
 
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
 
function numeric(str) {
  return parseInt(str, 10) == str
    ? parseInt(str, 10)
    : str.charCodeAt(0);
}
 
function escapeBraces(str) {
  return str.split('\\\\').join(escSlash)
            .split('\\{').join(escOpen)
            .split('\\}').join(escClose)
            .split('\\,').join(escComma)
            .split('\\.').join(escPeriod);
}
 
function unescapeBraces(str) {
  return str.split(escSlash).join('\\')
            .split(escOpen).join('{')
            .split(escClose).join('}')
            .split(escComma).join(',')
            .split(escPeriod).join('.');
}
 
 
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
  if (!str)
    return [''];
 
  var parts = [];
  var m = balanced('{', '}', str);
 
  if (!m)
    return str.split(',');
 
  var pre = m.pre;
  var body = m.body;
  var post = m.post;
  var p = pre.split(',');
 
  p[p.length-1] += '{' + body + '}';
  var postParts = parseCommaParts(post);
  if (post.length) {
    p[p.length-1] += postParts.shift();
    p.push.apply(p, postParts);
  }
 
  parts.push.apply(parts, p);
 
  return parts;
}
 
function expandTop(str) {
  if (!str)
    return [];
 
  // I don't know why Bash 4.3 does this, but it does.
  // Anything starting with {} will have the first two bytes preserved
  // but *only* at the top level, so {},a}b will not expand to anything,
  // but a{},b}c will be expanded to [a}c,abc].
  // One could argue that this is a bug in Bash, but since the goal of
  // this module is to match Bash's rules, we escape a leading {}
  if (str.substr(0, 2) === '{}') {
    str = '\\{\\}' + str.substr(2);
  }
 
  return expand(escapeBraces(str), true).map(unescapeBraces);
}
 
function identity(e) {
  return e;
}
 
function embrace(str) {
  return '{' + str + '}';
}
function isPadded(el) {
  return /^-?0\d/.test(el);
}
 
function lte(i, y) {
  return i <= y;
}
function gte(i, y) {
  return i >= y;
}
 
function expand(str, isTop) {
  var expansions = [];
 
  var m = balanced('{', '}', str);
  if (!m || /\$$/.test(m.pre)) return [str];
 
  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  var isSequence = isNumericSequence || isAlphaSequence;
  var isOptions = /^(.*,)+(.+)?$/.test(m.body);
  if (!isSequence && !isOptions) {
    // {a},b}
    if (m.post.match(/,.*\}/)) {
      str = m.pre + '{' + m.body + escClose + m.post;
      return expand(str);
    }
    return [str];
  }
 
  var n;
  if (isSequence) {
    n = m.body.split(/\.\./);
  } else {
    n = parseCommaParts(m.body);
    if (n.length === 1) {
      // x{{a,b}}y ==> x{a}y x{b}y
      n = expand(n[0], false).map(embrace);
      if (n.length === 1) {
        var post = m.post.length
          ? expand(m.post, false)
          : [''];
        return post.map(function(p) {
          return m.pre + n[0] + p;
        });
      }
    }
  }
 
  // at this point, n is the parts, and we know it's not a comma set
  // with a single entry.
 
  // no need to expand pre, since it is guaranteed to be free of brace-sets
  var pre = m.pre;
  var post = m.post.length
    ? expand(m.post, false)
    : [''];
 
  var N;
 
  if (isSequence) {
    var x = numeric(n[0]);
    var y = numeric(n[1]);
    var width = Math.max(n[0].length, n[1].length)
    var incr = n.length == 3
      ? Math.abs(numeric(n[2]))
      : 1;
    var test = lte;
    var reverse = y < x;
    if (reverse) {
      incr *= -1;
      test = gte;
    }
    var pad = n.some(isPadded);
 
    N = [];
 
    for (var i = x; test(i, y); i += incr) {
      var c;
      if (isAlphaSequence) {
        c = String.fromCharCode(i);
        if (c === '\\')
          c = '';
      } else {
        c = String(i);
        if (pad) {
          var need = width - c.length;
          if (need > 0) {
            var z = new Array(need + 1).join('0');
            if (i < 0)
              c = '-' + z + c.slice(1);
            else
              c = z + c;
          }
        }
      }
      N.push(c);
    }
  } else {
    N = concatMap(n, function(el) { return expand(el, false) });
  }
 
  for (var j = 0; j < N.length; j++) {
    for (var k = 0; k < post.length; k++) {
      var expansion = pre + N[j] + post[k];
      if (!isTop || isSequence || expansion)
        expansions.push(expansion);
    }
  }
 
  return expansions;
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/

Statements: 14.29% (5 / 35)      Branches: 0% (0 / 26)      Functions: 0% (0 / 3)      Lines: 15.15% (5 / 33)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/
File Statements Branches Functions Lines
index.js 14.29% (5 / 35) 0% (0 / 26) 0% (0 / 3) 15.15% (5 / 33)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js

Statements: 14.29% (5 / 35)      Branches: 0% (0 / 26)      Functions: 0% (0 / 3)      Lines: 15.15% (5 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601 1                             1         1 1                                                                          
module.exports = balanced;
function balanced(a, b, str) {
  if (a instanceof RegExp) a = maybeMatch(a, str);
  if (b instanceof RegExp) b = maybeMatch(b, str);
 
  var r = range(a, b, str);
 
  return r && {
    start: r[0],
    end: r[1],
    pre: str.slice(0, r[0]),
    body: str.slice(r[0] + a.length, r[1]),
    post: str.slice(r[1] + b.length)
  };
}
 
function maybeMatch(reg, str) {
  var m = str.match(reg);
  return m ? m[0] : null;
}
 
balanced.range = range;
function range(a, b, str) {
  var begs, beg, left, right, result;
  var ai = str.indexOf(a);
  var bi = str.indexOf(b, ai + 1);
  var i = ai;
 
  if (ai >= 0 && bi > 0) {
    begs = [];
    left = str.length;
 
    while (i >= 0 && !result) {
      if (i == ai) {
        begs.push(i);
        ai = str.indexOf(a, i + 1);
      } else if (begs.length == 1) {
        result = [ begs.pop(), bi ];
      } else {
        beg = begs.pop();
        if (beg < left) {
          left = beg;
          right = bi;
        }
 
        bi = str.indexOf(b, i + 1);
      }
 
      i = ai < bi && ai >= 0 ? ai : bi;
    }
 
    if (begs.length) {
      result = [ left, right ];
    }
  }
 
  return result;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/

Statements: 20% (2 / 10)      Branches: 25% (1 / 4)      Functions: 0% (0 / 2)      Lines: 22.22% (2 / 9)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/
File Statements Branches Functions Lines
index.js 20% (2 / 10) 25% (1 / 4) 0% (0 / 2) 22.22% (2 / 9)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js

Statements: 20% (2 / 10)      Branches: 25% (1 / 4)      Functions: 0% (0 / 2)      Lines: 22.22% (2 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 151                   1        
module.exports = function (xs, fn) {
    var res = [];
    for (var i = 0; i < xs.length; i++) {
        var x = fn(xs[i], i);
        if (isArray(x)) res.push.apply(res, x);
        else res.push(x);
    }
    return res;
};
 
var isArray = Array.isArray || function (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/path-is-absolute/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/path-is-absolute/

Statements: 45.45% (5 / 11)      Branches: 12.5% (1 / 8)      Functions: 0% (0 / 2)      Lines: 45.45% (5 / 11)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/path-is-absolute/
File Statements Branches Functions Lines
index.js 45.45% (5 / 11) 12.5% (1 / 8) 0% (0 / 2) 45.45% (5 / 11)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/path-is-absolute/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/glob/node_modules/path-is-absolute/index.js

Statements: 45.45% (5 / 11)      Branches: 12.5% (1 / 8)      Functions: 0% (0 / 2)      Lines: 45.45% (5 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22    1       1                     1 1 1    
'use strict';
 
function posix(path) {
	return path.charAt(0) === '/';
}
 
function win32(path) {
	// https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
	var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
	var result = splitDeviceRe.exec(path);
	var device = result[1] || '';
	var isUnc = Boolean(device && device.charAt(1) !== ':');
 
	// UNC paths are always absolute
	return Boolean(result[2] || isUnc);
}
 
module.exports = process.platform === 'win32' ? win32 : posix;
module.exports.posix = posix;
module.exports.win32 = win32;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/

Statements: 36.5% (165 / 452)      Branches: 14.71% (35 / 238)      Functions: 22.73% (20 / 88)      Lines: 37.95% (159 / 419)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/
File Statements Branches Functions Lines
fs.js 81.82% (9 / 11) 66.67% (4 / 6) 100% (2 / 2) 81.82% (9 / 11)
graceful-fs.js 41.72% (68 / 163) 9.88% (8 / 81) 14.71% (5 / 34) 41.72% (68 / 163)
legacy-streams.js 6.85% (5 / 73) 0% (0 / 32) 0% (0 / 5) 7.14% (5 / 70)
polyfills.js 40.49% (83 / 205) 19.33% (23 / 119) 27.66% (13 / 47) 44% (77 / 175)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/fs.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/fs.js

Statements: 81.82% (9 / 11)      Branches: 66.67% (4 / 6)      Functions: 100% (2 / 2)      Lines: 81.82% (9 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23    1   1   1 1     1 1       1 82     1      
'use strict'
 
var fs = require('fs')
 
module.exports = clone(fs)
 
function clone (obj) {
  Iif (obj === null || typeof obj !== 'object')
    return obj
 
  Eif (obj instanceof Object)
    var copy = { __proto__: obj.__proto__ }
  else
    var copy = Object.create(null)
 
  Object.getOwnPropertyNames(obj).forEach(function (key) {
    Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
  })
 
  return copy
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/graceful-fs.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/graceful-fs.js

Statements: 41.72% (68 / 163)      Branches: 9.88% (8 / 81)      Functions: 14.71% (5 / 34)      Lines: 41.72% (68 / 163)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 2641 1 1 1   1   1   1 1 1               1             1 1               1 1                   1 1     795 795 795     1   2 2 2 2 2 2 2 2 1           1                         2 2 1           1                         2 2 2 1           1                         2 2 1                     1                           1       2           2 2 2   2 2 2   2 2   1             1                               1             1                         1       1       2 2 1           1                         2     1         1 795 795            
var fs = require('fs')
var polyfills = require('./polyfills.js')
var legacy = require('./legacy-streams.js')
var queue = []
 
var util = require('util')
 
function noop () {}
 
var debug = noop
Eif (util.debuglog)
  debug = util.debuglog('gfs4')
else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
  debug = function() {
    var m = util.format.apply(util, arguments)
    m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
    console.error(m)
  }
 
Iif (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
  process.on('exit', function() {
    debug(queue)
    require('assert').equal(queue.length, 0)
  })
}
 
module.exports = patch(require('./fs.js'))
Iif (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) {
  module.exports = patch(fs)
}
 
// Always patch fs.close/closeSync, because we want to
// retry() whenever a close happens *anywhere* in the program.
// This is essential when multiple graceful-fs instances are
// in play at the same time.
module.exports.close =
fs.close = (function (fs$close) { return function (fd, cb) {
  return fs$close.call(fs, fd, function (err) {
    if (!err)
      retry()
 
    if (typeof cb === 'function')
      cb.apply(this, arguments)
  })
}})(fs.close)
 
module.exports.closeSync =
fs.closeSync = (function (fs$closeSync) { return function (fd) {
  // Note that graceful-fs also retries when fs.closeSync() fails.
  // Looks like a bug to me, although it's probably a harmless one.
  var rval = fs$closeSync.apply(fs, arguments)
  retry()
  return rval
}})(fs.closeSync)
 
function patch (fs) {
  // Everything that references the open() function needs to be in here
  polyfills(fs)
  fs.gracefulify = patch
  fs.FileReadStream = ReadStream;  // Legacy name.
  fs.FileWriteStream = WriteStream;  // Legacy name.
  fs.createReadStream = createReadStream
  fs.createWriteStream = createWriteStream
  var fs$readFile = fs.readFile
  fs.readFile = readFile
  function readFile (path, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null
 
    return go$readFile(path, options, cb)
 
    function go$readFile (path, options, cb) {
      return fs$readFile(path, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$readFile, [path, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }
 
  var fs$writeFile = fs.writeFile
  fs.writeFile = writeFile
  function writeFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null
 
    return go$writeFile(path, data, options, cb)
 
    function go$writeFile (path, data, options, cb) {
      return fs$writeFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$writeFile, [path, data, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }
 
  var fs$appendFile = fs.appendFile
  Eif (fs$appendFile)
    fs.appendFile = appendFile
  function appendFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null
 
    return go$appendFile(path, data, options, cb)
 
    function go$appendFile (path, data, options, cb) {
      return fs$appendFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$appendFile, [path, data, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }
 
  var fs$readdir = fs.readdir
  fs.readdir = readdir
  function readdir (path, options, cb) {
    var args = [path]
    if (typeof options !== 'function') {
      args.push(options)
    } else {
      cb = options
    }
    args.push(go$readdir$cb)
 
    return go$readdir(args)
 
    function go$readdir$cb (err, files) {
      if (files && files.sort)
        files.sort()
 
      if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
        enqueue([go$readdir, [args]])
      else {
        if (typeof cb === 'function')
          cb.apply(this, arguments)
        retry()
      }
    }
  }
 
  function go$readdir (args) {
    return fs$readdir.apply(fs, args)
  }
 
  Iif (process.version.substr(0, 4) === 'v0.8') {
    var legStreams = legacy(fs)
    ReadStream = legStreams.ReadStream
    WriteStream = legStreams.WriteStream
  }
 
  var fs$ReadStream = fs.ReadStream
  ReadStream.prototype = Object.create(fs$ReadStream.prototype)
  ReadStream.prototype.open = ReadStream$open
 
  var fs$WriteStream = fs.WriteStream
  WriteStream.prototype = Object.create(fs$WriteStream.prototype)
  WriteStream.prototype.open = WriteStream$open
 
  fs.ReadStream = ReadStream
  fs.WriteStream = WriteStream
 
  function ReadStream (path, options) {
    if (this instanceof ReadStream)
      return fs$ReadStream.apply(this, arguments), this
    else
      return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
  }
 
  function ReadStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        if (that.autoClose)
          that.destroy()
 
        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
        that.read()
      }
    })
  }
 
  function WriteStream (path, options) {
    if (this instanceof WriteStream)
      return fs$WriteStream.apply(this, arguments), this
    else
      return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
  }
 
  function WriteStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        that.destroy()
        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
      }
    })
  }
 
  function createReadStream (path, options) {
    return new ReadStream(path, options)
  }
 
  function createWriteStream (path, options) {
    return new WriteStream(path, options)
  }
 
  var fs$open = fs.open
  fs.open = open
  function open (path, flags, mode, cb) {
    if (typeof mode === 'function')
      cb = mode, mode = null
 
    return go$open(path, flags, mode, cb)
 
    function go$open (path, flags, mode, cb) {
      return fs$open(path, flags, mode, function (err, fd) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$open, [path, flags, mode, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }
 
  return fs
}
 
function enqueue (elem) {
  debug('ENQUEUE', elem[0].name, elem[1])
  queue.push(elem)
}
 
function retry () {
  var elem = queue.shift()
  Iif (elem) {
    debug('RETRY', elem[0].name, elem[1])
    elem[0].apply(null, elem[1])
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/legacy-streams.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/legacy-streams.js

Statements: 6.85% (5 / 73)      Branches: 0% (0 / 32)      Functions: 0% (0 / 5)      Lines: 7.14% (5 / 70)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 1201   1   1           1                                                                                                                               1                                                                                          
var Stream = require('stream').Stream
 
module.exports = legacy
 
function legacy (fs) {
  return {
    ReadStream: ReadStream,
    WriteStream: WriteStream
  }
 
  function ReadStream (path, options) {
    if (!(this instanceof ReadStream)) return new ReadStream(path, options);
 
    Stream.call(this);
 
    var self = this;
 
    this.path = path;
    this.fd = null;
    this.readable = true;
    this.paused = false;
 
    this.flags = 'r';
    this.mode = 438; /*=0666*/
    this.bufferSize = 64 * 1024;
 
    options = options || {};
 
    // Mixin options into this
    var keys = Object.keys(options);
    for (var index = 0, length = keys.length; index < length; index++) {
      var key = keys[index];
      this[key] = options[key];
    }
 
    if (this.encoding) this.setEncoding(this.encoding);
 
    if (this.start !== undefined) {
      if ('number' !== typeof this.start) {
        throw TypeError('start must be a Number');
      }
      if (this.end === undefined) {
        this.end = Infinity;
      } else if ('number' !== typeof this.end) {
        throw TypeError('end must be a Number');
      }
 
      if (this.start > this.end) {
        throw new Error('start must be <= end');
      }
 
      this.pos = this.start;
    }
 
    if (this.fd !== null) {
      process.nextTick(function() {
        self._read();
      });
      return;
    }
 
    fs.open(this.path, this.flags, this.mode, function (err, fd) {
      if (err) {
        self.emit('error', err);
        self.readable = false;
        return;
      }
 
      self.fd = fd;
      self.emit('open', fd);
      self._read();
    })
  }
 
  function WriteStream (path, options) {
    if (!(this instanceof WriteStream)) return new WriteStream(path, options);
 
    Stream.call(this);
 
    this.path = path;
    this.fd = null;
    this.writable = true;
 
    this.flags = 'w';
    this.encoding = 'binary';
    this.mode = 438; /*=0666*/
    this.bytesWritten = 0;
 
    options = options || {};
 
    // Mixin options into this
    var keys = Object.keys(options);
    for (var index = 0, length = keys.length; index < length; index++) {
      var key = keys[index];
      this[key] = options[key];
    }
 
    if (this.start !== undefined) {
      if ('number' !== typeof this.start) {
        throw TypeError('start must be a Number');
      }
      if (this.start < 0) {
        throw new Error('start must be >= zero');
      }
 
      this.pos = this.start;
    }
 
    this.busy = false;
    this._queue = [];
 
    if (this.fd === null) {
      this._open = fs.open;
      this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
      this.flush();
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/polyfills.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/graceful-fs/polyfills.js

Statements: 40.49% (83 / 205)      Branches: 19.33% (23 / 119)      Functions: 27.66% (13 / 47)      Lines: 44% (77 / 175)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 3321 1   1 1   1   1 7 1 7   1 1     1 1         1   1         2           2 2               2 2 2   2 2 2   2 2 2   2 2 2   2 2 2   2 2 2     2 2     2   2 2     2                       2                                                   2                             2 774 774 774 774                       1                                                                                     1 2                                                                     2 2       1 6 4               1 6 4                   1 6 4               1 6 4                   1 6     6                   1 6     6 1578 1578 1578 1578                               1                                
var fs = require('./fs.js')
var constants = require('constants')
 
var origCwd = process.cwd
var cwd = null
 
var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform
 
process.cwd = function() {
  if (!cwd)
    cwd = origCwd.call(process)
  return cwd
}
try {
  process.cwd()
} catch (er) {}
 
var chdir = process.chdir
process.chdir = function(d) {
  cwd = null
  chdir.call(process, d)
}
 
module.exports = patch
 
function patch (fs) {
  // (re-)implement some things that are known busted or missing.
 
  // lchmod, broken prior to 0.6.2
  // back-port the fix here.
  Iif (constants.hasOwnProperty('O_SYMLINK') &&
      process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
    patchLchmod(fs)
  }
 
  // lutimes implementation, or no-op
  Eif (!fs.lutimes) {
    patchLutimes(fs)
  }
 
  // https://github.com/isaacs/node-graceful-fs/issues/4
  // Chown should not fail on einval or eperm if non-root.
  // It should not fail on enosys ever, as this just indicates
  // that a fs doesn't support the intended operation.
 
  fs.chown = chownFix(fs.chown)
  fs.fchown = chownFix(fs.fchown)
  fs.lchown = chownFix(fs.lchown)
 
  fs.chmod = chmodFix(fs.chmod)
  fs.fchmod = chmodFix(fs.fchmod)
  fs.lchmod = chmodFix(fs.lchmod)
 
  fs.chownSync = chownFixSync(fs.chownSync)
  fs.fchownSync = chownFixSync(fs.fchownSync)
  fs.lchownSync = chownFixSync(fs.lchownSync)
 
  fs.chmodSync = chmodFixSync(fs.chmodSync)
  fs.fchmodSync = chmodFixSync(fs.fchmodSync)
  fs.lchmodSync = chmodFixSync(fs.lchmodSync)
 
  fs.stat = statFix(fs.stat)
  fs.fstat = statFix(fs.fstat)
  fs.lstat = statFix(fs.lstat)
 
  fs.statSync = statFixSync(fs.statSync)
  fs.fstatSync = statFixSync(fs.fstatSync)
  fs.lstatSync = statFixSync(fs.lstatSync)
 
  // if lchmod/lchown do not exist, then make them no-ops
  Eif (!fs.lchmod) {
    fs.lchmod = function (path, mode, cb) {
      if (cb) process.nextTick(cb)
    }
    fs.lchmodSync = function () {}
  }
  Eif (!fs.lchown) {
    fs.lchown = function (path, uid, gid, cb) {
      if (cb) process.nextTick(cb)
    }
    fs.lchownSync = function () {}
  }
 
  // on Windows, A/V software can lock the directory, causing this
  // to fail with an EACCES or EPERM if the directory contains newly
  // created files.  Try again on failure, for up to 60 seconds.
 
  // Set the timeout this long because some Windows Anti-Virus, such as Parity
  // bit9, may lock files for up to a minute, causing npm package install
  // failures. Also, take care to yield the scheduler. Windows scheduling gives
  // CPU to a busy looping process, which can cause the program causing the lock
  // contention to be starved of CPU by node, so the contention doesn't resolve.
  Iif (platform === "win32") {
    fs.rename = (function (fs$rename) { return function (from, to, cb) {
      var start = Date.now()
      var backoff = 0;
      fs$rename(from, to, function CB (er) {
        if (er
            && (er.code === "EACCES" || er.code === "EPERM")
            && Date.now() - start < 60000) {
          setTimeout(function() {
            fs.stat(to, function (stater, st) {
              if (stater && stater.code === "ENOENT")
                fs$rename(from, to, CB);
              else
                cb(er)
            })
          }, backoff)
          if (backoff < 100)
            backoff += 10;
          return;
        }
        if (cb) cb(er)
      })
    }})(fs.rename)
  }
 
  // if read() returns EAGAIN, then just try it again.
  fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) {
    var callback
    if (callback_ && typeof callback_ === 'function') {
      var eagCounter = 0
      callback = function (er, _, __) {
        if (er && er.code === 'EAGAIN' && eagCounter < 10) {
          eagCounter ++
          return fs$read.call(fs, fd, buffer, offset, length, position, callback)
        }
        callback_.apply(this, arguments)
      }
    }
    return fs$read.call(fs, fd, buffer, offset, length, position, callback)
  }})(fs.read)
 
  fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
    var eagCounter = 0
    while (true) {
      try {
        return fs$readSync.call(fs, fd, buffer, offset, length, position)
      } catch (er) {
        if (er.code === 'EAGAIN' && eagCounter < 10) {
          eagCounter ++
          continue
        }
        throw er
      }
    }
  }})(fs.readSync)
}
 
function patchLchmod (fs) {
  fs.lchmod = function (path, mode, callback) {
    fs.open( path
           , constants.O_WRONLY | constants.O_SYMLINK
           , mode
           , function (err, fd) {
      if (err) {
        if (callback) callback(err)
        return
      }
      // prefer to return the chmod error, if one occurs,
      // but still try to close, and report closing errors if they occur.
      fs.fchmod(fd, mode, function (err) {
        fs.close(fd, function(err2) {
          if (callback) callback(err || err2)
        })
      })
    })
  }
 
  fs.lchmodSync = function (path, mode) {
    var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
 
    // prefer to return the chmod error, if one occurs,
    // but still try to close, and report closing errors if they occur.
    var threw = true
    var ret
    try {
      ret = fs.fchmodSync(fd, mode)
      threw = false
    } finally {
      if (threw) {
        try {
          fs.closeSync(fd)
        } catch (er) {}
      } else {
        fs.closeSync(fd)
      }
    }
    return ret
  }
}
 
function patchLutimes (fs) {
  Iif (constants.hasOwnProperty("O_SYMLINK")) {
    fs.lutimes = function (path, at, mt, cb) {
      fs.open(path, constants.O_SYMLINK, function (er, fd) {
        if (er) {
          if (cb) cb(er)
          return
        }
        fs.futimes(fd, at, mt, function (er) {
          fs.close(fd, function (er2) {
            if (cb) cb(er || er2)
          })
        })
      })
    }
 
    fs.lutimesSync = function (path, at, mt) {
      var fd = fs.openSync(path, constants.O_SYMLINK)
      var ret
      var threw = true
      try {
        ret = fs.futimesSync(fd, at, mt)
        threw = false
      } finally {
        if (threw) {
          try {
            fs.closeSync(fd)
          } catch (er) {}
        } else {
          fs.closeSync(fd)
        }
      }
      return ret
    }
 
  } else {
    fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
    fs.lutimesSync = function () {}
  }
}
 
function chmodFix (orig) {
  if (!orig) return orig
  return function (target, mode, cb) {
    return orig.call(fs, target, mode, function (er) {
      if (chownErOk(er)) er = null
      if (cb) cb.apply(this, arguments)
    })
  }
}
 
function chmodFixSync (orig) {
  if (!orig) return orig
  return function (target, mode) {
    try {
      return orig.call(fs, target, mode)
    } catch (er) {
      if (!chownErOk(er)) throw er
    }
  }
}
 
 
function chownFix (orig) {
  if (!orig) return orig
  return function (target, uid, gid, cb) {
    return orig.call(fs, target, uid, gid, function (er) {
      if (chownErOk(er)) er = null
      if (cb) cb.apply(this, arguments)
    })
  }
}
 
function chownFixSync (orig) {
  if (!orig) return orig
  return function (target, uid, gid) {
    try {
      return orig.call(fs, target, uid, gid)
    } catch (er) {
      if (!chownErOk(er)) throw er
    }
  }
}
 
 
function statFix (orig) {
  Iif (!orig) return orig
  // Older versions of Node erroneously returned signed integers for
  // uid + gid.
  return function (target, cb) {
    return orig.call(fs, target, function (er, stats) {
      if (!stats) return cb.apply(this, arguments)
      if (stats.uid < 0) stats.uid += 0x100000000
      if (stats.gid < 0) stats.gid += 0x100000000
      if (cb) cb.apply(this, arguments)
    })
  }
}
 
function statFixSync (orig) {
  Iif (!orig) return orig
  // Older versions of Node erroneously returned signed integers for
  // uid + gid.
  return function (target) {
    var stats = orig.call(fs, target)
    Iif (stats.uid < 0) stats.uid += 0x100000000
    Iif (stats.gid < 0) stats.gid += 0x100000000
    return stats;
  }
}
 
// ENOSYS means that the fs doesn't support the op. Just ignore
// that, because it doesn't matter.
//
// if there's no getuid, or if getuid() is something other
// than 0, and the error is EINVAL or EPERM, then just ignore
// it.
//
// This specific case is a silent failure in cp, install, tar,
// and most other unix tools that manage permissions.
//
// When running as root, or if other types of errors are
// encountered, then it's strict.
function chownErOk (er) {
  if (!er)
    return true
 
  if (er.code === "ENOSYS")
    return true
 
  var nonroot = !process.getuid || process.getuid() !== 0
  if (nonroot) {
    if (er.code === "EINVAL" || er.code === "EPERM")
      return true
  }
 
  return false
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/has-unicode/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/has-unicode/

Statements: 85.71% (6 / 7)      Branches: 40% (2 / 5)      Functions: 100% (1 / 1)      Lines: 100% (6 / 6)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/has-unicode/
File Statements Branches Functions Lines
index.js 85.71% (6 / 7) 40% (2 / 5) 100% (1 / 1) 100% (6 / 6)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/has-unicode/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/has-unicode/index.js

Statements: 85.71% (6 / 7)      Branches: 40% (2 / 5)      Functions: 100% (1 / 1)      Lines: 100% (6 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  1   1             2   2 2 2      
"use strict"
var os = require("os")
 
var hasUnicode = module.exports = function () {
  // Recent Win32 platforms (>XP) CAN support unicode in the console but
  // don't have to, and in non-english locales often use traditional local
  // code pages. There's no way, short of windows system calls or execing
  // the chcp command line program to figure this out. As such, we default
  // this to false and encourage your users to override it via config if
  // appropriate.
  Iif (os.type() == "Windows_NT") { return false }
 
  var isUTF8 = /UTF-?8$/i
  var ctype = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG
  return isUTF8.test(ctype)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/

Statements: 26.21% (38 / 145)      Branches: 3.8% (3 / 79)      Functions: 10% (3 / 30)      Lines: 28.46% (37 / 130)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/
File Statements Branches Functions Lines
git-host-info.js 100% (9 / 9) 100% (2 / 2) 100% (3 / 3) 100% (8 / 8)
git-host.js 26.76% (19 / 71) 3.57% (1 / 28) 0% (0 / 20) 27.54% (19 / 69)
index.js 15.38% (10 / 65) 0% (0 / 49) 0% (0 / 7) 18.87% (10 / 53)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/git-host-info.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/git-host-info.js

Statements: 100% (9 / 9)      Branches: 100% (2 / 2)      Functions: 100% (3 / 3)      Lines: 100% (8 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70    1                                                                                       1                       1 4 36 25   4   19        
'use strict'
 
var gitHosts = module.exports = {
  github: {
    // First two are insecure and generally shouldn't be used any more, but
    // they are still supported.
    'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ],
    'domain': 'github.com',
    'treepath': 'tree',
    'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}',
    'bugstemplate': 'https://{domain}/{user}/{project}/issues',
    'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}',
    'tarballtemplate': 'https://{domain}/{user}/{project}/archive/{committish}.tar.gz'
  },
  bitbucket: {
    'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
    'domain': 'bitbucket.org',
    'treepath': 'src',
    'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz'
  },
  gitlab: {
    'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
    'domain': 'gitlab.com',
    'treepath': 'tree',
    'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#README',
    'bugstemplate': 'https://{domain}/{user}/{project}/issues',
    'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}'
  },
  gist: {
    'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ],
    'domain': 'gist.github.com',
    'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]+)(?:[.]git)?$/,
    'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}',
    'bugstemplate': 'https://{domain}/{project}',
    'gittemplate': 'git://{domain}/{project}.git{#committish}',
    'sshtemplate': 'git@{domain}:/{project}.git{#committish}',
    'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}',
    'browsetemplate': 'https://{domain}/{project}{/committish}',
    'docstemplate': 'https://{domain}/{project}{/committish}',
    'httpstemplate': 'git+https://{domain}/{project}.git{#committish}',
    'shortcuttemplate': '{type}:{project}{#committish}',
    'pathtemplate': '{project}{#committish}',
    'tarballtemplate': 'https://{domain}/{user}/{project}/archive/{committish}.tar.gz'
  }
}
 
var gitHostDefaults = {
  'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}',
  'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}',
  'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}',
  'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme',
  'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}',
  'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}',
  'shortcuttemplate': '{type}:{user}/{project}{#committish}',
  'pathtemplate': '{user}/{project}{#committish}',
  'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/
}
 
Object.keys(gitHosts).forEach(function (name) {
  Object.keys(gitHostDefaults).forEach(function (key) {
    if (gitHosts[name][key]) return
    gitHosts[name][key] = gitHostDefaults[key]
  })
  gitHosts[name].protocols_re = RegExp('^(' +
    gitHosts[name].protocols.map(function (protocol) {
      return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1')
    }).join('|') + '):$')
})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/git-host.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/git-host.js

Statements: 26.76% (19 / 71)      Branches: 3.57% (1 / 28)      Functions: 0% (0 / 20)      Lines: 27.54% (19 / 69)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116  1 1   1                         1   1       1                                                                           1       1       1       1       1       1       1       1       1       1       1           1       1        
'use strict'
var gitHosts = require('./git-host-info.js')
var extend = Object.assign || require('util')._extend
 
var GitHost = module.exports = function (type, user, auth, project, committish, defaultRepresentation, opts) {
  var gitHostInfo = this
  gitHostInfo.type = type
  Object.keys(gitHosts[type]).forEach(function (key) {
    gitHostInfo[key] = gitHosts[type][key]
  })
  gitHostInfo.user = user
  gitHostInfo.auth = auth
  gitHostInfo.project = project
  gitHostInfo.committish = committish
  gitHostInfo.default = defaultRepresentation
  gitHostInfo.opts = opts || {}
}
GitHost.prototype = {}
 
GitHost.prototype.hash = function () {
  return this.committish ? '#' + this.committish : ''
}
 
GitHost.prototype._fill = function (template, opts) {
  if (!template) return
  var vars = extend({}, opts)
  opts = extend(extend({}, this.opts), opts)
  var self = this
  Object.keys(this).forEach(function (key) {
    if (self[key] != null && vars[key] == null) vars[key] = self[key]
  })
  var rawAuth = vars.auth
  var rawComittish = vars.committish
  Object.keys(vars).forEach(function (key) {
    vars[key] = encodeURIComponent(vars[key])
  })
  vars['auth@'] = rawAuth ? rawAuth + '@' : ''
  if (opts.noCommittish) {
    vars['#committish'] = ''
    vars['/tree/committish'] = ''
    vars['/comittish'] = ''
    vars.comittish = ''
  } else {
    vars['#committish'] = rawComittish ? '#' + rawComittish : ''
    vars['/tree/committish'] = vars.committish
                            ? '/' + vars.treepath + '/' + vars.committish
                            : ''
    vars['/committish'] = vars.committish ? '/' + vars.committish : ''
    vars.committish = vars.committish || 'master'
  }
  var res = template
  Object.keys(vars).forEach(function (key) {
    res = res.replace(new RegExp('[{]' + key + '[}]', 'g'), vars[key])
  })
  if (opts.noGitPlus) {
    return res.replace(/^git[+]/, '')
  } else {
    return res
  }
}
 
GitHost.prototype.ssh = function (opts) {
  return this._fill(this.sshtemplate, opts)
}
 
GitHost.prototype.sshurl = function (opts) {
  return this._fill(this.sshurltemplate, opts)
}
 
GitHost.prototype.browse = function (opts) {
  return this._fill(this.browsetemplate, opts)
}
 
GitHost.prototype.docs = function (opts) {
  return this._fill(this.docstemplate, opts)
}
 
GitHost.prototype.bugs = function (opts) {
  return this._fill(this.bugstemplate, opts)
}
 
GitHost.prototype.https = function (opts) {
  return this._fill(this.httpstemplate, opts)
}
 
GitHost.prototype.git = function (opts) {
  return this._fill(this.gittemplate, opts)
}
 
GitHost.prototype.shortcut = function (opts) {
  return this._fill(this.shortcuttemplate, opts)
}
 
GitHost.prototype.path = function (opts) {
  return this._fill(this.pathtemplate, opts)
}
 
GitHost.prototype.tarball = function (opts) {
  return this._fill(this.tarballtemplate, opts)
}
 
GitHost.prototype.file = function (P, opts) {
  return this._fill(this.filetemplate, extend({
    path: P.replace(/^[/]+/g, '')
  }, opts))
}
 
GitHost.prototype.getDefaultRepresentation = function () {
  return this.default
}
 
GitHost.prototype.toString = function (opts) {
  return (this[this.default] || this.sshurl).call(this, opts)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/hosted-git-info/index.js

Statements: 15.38% (10 / 65)      Branches: 0% (0 / 49)      Functions: 0% (0 / 7)      Lines: 18.87% (10 / 53)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111  1 1 1   1             1         1               1                                                                                   1                       1                   1                                          
'use strict'
var url = require('url')
var gitHosts = require('./git-host-info.js')
var GitHost = module.exports = require('./git-host.js')
 
var protocolToRepresentationMap = {
  'git+ssh': 'sshurl',
  'git+https': 'https',
  'ssh': 'sshurl',
  'git': 'git'
}
 
function protocolToRepresentation (protocol) {
  if (protocol.substr(-1) === ':') protocol = protocol.slice(0, -1)
  return protocolToRepresentationMap[protocol] || protocol
}
 
var authProtocols = {
  'git:': true,
  'https:': true,
  'git+https:': true,
  'http:': true,
  'git+http:': true
}
 
module.exports.fromUrl = function (giturl, opts) {
  if (giturl == null || giturl === '') return
  var url = fixupUnqualifiedGist(
    isGitHubShorthand(giturl) ? 'github:' + giturl : giturl
  )
  var parsed = parseGitUrl(url)
  var shortcutMatch = url.match(new RegExp('^([^:]+):(?:(?:[^@:]+(?:[^@]+)?@)?([^/]*))[/](.+?)(?:[.]git)?($|#)'))
  var matches = Object.keys(gitHosts).map(function (gitHostName) {
    try {
      var gitHostInfo = gitHosts[gitHostName]
      var auth = null
      if (parsed.auth && authProtocols[parsed.protocol]) {
        auth = decodeURIComponent(parsed.auth)
      }
      var committish = parsed.hash ? decodeURIComponent(parsed.hash.substr(1)) : null
      var user = null
      var project = null
      var defaultRepresentation = null
      if (shortcutMatch && shortcutMatch[1] === gitHostName) {
        user = shortcutMatch[2] && decodeURIComponent(shortcutMatch[2])
        project = decodeURIComponent(shortcutMatch[3])
        defaultRepresentation = 'shortcut'
      } else {
        if (parsed.host !== gitHostInfo.domain) return
        if (!gitHostInfo.protocols_re.test(parsed.protocol)) return
        if (!parsed.path) return
        var pathmatch = gitHostInfo.pathmatch
        var matched = parsed.path.match(pathmatch)
        if (!matched) return
        if (matched[1] != null) user = decodeURIComponent(matched[1])
        if (matched[2] != null) project = decodeURIComponent(matched[2])
        defaultRepresentation = protocolToRepresentation(parsed.protocol)
      }
      return new GitHost(gitHostName, user, auth, project, committish, defaultRepresentation, opts)
    } catch (ex) {
      if (!(ex instanceof URIError)) throw ex
    }
  }).filter(function (gitHostInfo) { return gitHostInfo })
  if (matches.length !== 1) return
  return matches[0]
}
 
function isGitHubShorthand (arg) {
  // Note: This does not fully test the git ref format.
  // See https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
  //
  // The only way to do this properly would be to shell out to
  // git-check-ref-format, and as this is a fast sync function,
  // we don't want to do that.  Just let git fail if it turns
  // out that the commit-ish is invalid.
  // GH usernames cannot start with . or -
  return /^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(arg)
}
 
function fixupUnqualifiedGist (giturl) {
  // necessary for round-tripping gists
  var parsed = url.parse(giturl)
  if (parsed.protocol === 'gist:' && parsed.host && !parsed.path) {
    return parsed.protocol + '/' + parsed.host
  } else {
    return giturl
  }
}
 
function parseGitUrl (giturl) {
  if (typeof giturl !== 'string') giturl = '' + giturl
  var matched = giturl.match(/^([^@]+)@([^:/]+):[/]?((?:[^/]+[/])?[^/]+?)(?:[.]git)?(#.*)?$/)
  if (!matched) return url.parse(giturl)
  return {
    protocol: 'git+ssh:',
    slashes: true,
    auth: matched[1],
    host: matched[2],
    port: null,
    hostname: matched[2],
    hash: matched[4],
    search: null,
    query: null,
    pathname: '/' + matched[3],
    path: '/' + matched[3],
    href: 'git+ssh://' + matched[1] + '@' + matched[2] +
          '/' + matched[3] + (matched[4] || '')
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/iferr/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/iferr/

Statements: 46.15% (12 / 26)      Branches: 0% (0 / 10)      Functions: 28.57% (2 / 7)      Lines: 46.15% (12 / 26)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/iferr/
File Statements Branches Functions Lines
index.js 46.15% (12 / 26) 0% (0 / 10) 28.57% (2 / 7) 46.15% (12 / 26)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/iferr/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/iferr/index.js

Statements: 46.15% (12 / 26)      Branches: 0% (0 / 10)      Functions: 28.57% (2 / 7)      Lines: 46.15% (12 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51  1 1     1 1                     1                         1       1       1   1   1   1   1        
// Generated by CoffeeScript 1.7.1
(function() {
  var exports, iferr, printerr, throwerr, tiferr,
    __slice = [].slice;
 
  iferr = function(fail, succ) {
    return function() {
      var a, err;
      err = arguments[0], a = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      if (err != null) {
        return fail(err);
      } else {
        return typeof succ === "function" ? succ.apply(null, a) : void 0;
      }
    };
  };
 
  tiferr = function(fail, succ) {
    return iferr(fail, function() {
      var a, err;
      a = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      try {
        return succ.apply(null, a);
      } catch (_error) {
        err = _error;
        return fail(err);
      }
    });
  };
 
  throwerr = iferr.bind(null, function(err) {
    throw err;
  });
 
  printerr = iferr(function(err) {
    return console.error(err.stack || err);
  });
 
  module.exports = exports = iferr;
 
  exports.iferr = iferr;
 
  exports.tiferr = tiferr;
 
  exports.throwerr = throwerr;
 
  exports.printerr = printerr;
 
}).call(this);
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/imurmurhash/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/imurmurhash/

Statements: 23.19% (16 / 69)      Branches: 17.14% (6 / 35)      Functions: 60% (3 / 5)      Lines: 23.19% (16 / 69)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/imurmurhash/
File Statements Branches Functions Lines
imurmurhash.js 23.19% (16 / 69) 17.14% (6 / 35) 60% (3 / 5) 23.19% (16 / 69)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/imurmurhash/imurmurhash.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/imurmurhash/imurmurhash.js

Statements: 23.19% (16 / 69)      Branches: 17.14% (6 / 35)      Functions: 60% (3 / 5)      Lines: 23.19% (16 / 69)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140                      1 1               1 1 1 1       1                 1                                                                                                                     1                                                     1 1 1 1         1   1 1            
/**
 * @preserve
 * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013)
 *
 * @author <a href="mailto:jensyt@gmail.com">Jens Taylor</a>
 * @see http://github.com/homebrewing/brauhaus-diff
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @see http://github.com/garycourt/murmurhash-js
 * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
 * @see http://sites.google.com/site/murmurhash/
 */
(function(){
    var cache;
 
    // Call this function without `new` to use the cached object (good for
    // single-threaded environments), or with `new` to create a new object.
    //
    // @param {string} key A UTF-16 or ASCII string
    // @param {number} seed An optional positive integer
    // @return {object} A MurmurHash3 object for incremental hashing
    function MurmurHash3(key, seed) {
        var m = this instanceof MurmurHash3 ? this : cache;
        m.reset(seed)
        Iif (typeof key === 'string' && key.length > 0) {
            m.hash(key);
        }
 
        Iif (m !== this) {
            return m;
        }
    };
 
    // Incrementally add a string to this hash
    //
    // @param {string} key A UTF-16 or ASCII string
    // @return {object} this
    MurmurHash3.prototype.hash = function(key) {
        var h1, k1, i, top, len;
 
        len = key.length;
        this.len += len;
 
        k1 = this.k1;
        i = 0;
        switch (this.rem) {
            case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0;
            case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0;
            case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0;
            case 3:
                k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0;
                k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0;
        }
 
        this.rem = (len + this.rem) & 3; // & 3 is same as % 4
        len -= this.rem;
        if (len > 0) {
            h1 = this.h1;
            while (1) {
                k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff;
                k1 = (k1 << 15) | (k1 >>> 17);
                k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff;
 
                h1 ^= k1;
                h1 = (h1 << 13) | (h1 >>> 19);
                h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff;
 
                if (i >= len) {
                    break;
                }
 
                k1 = ((key.charCodeAt(i++) & 0xffff)) ^
                     ((key.charCodeAt(i++) & 0xffff) << 8) ^
                     ((key.charCodeAt(i++) & 0xffff) << 16);
                top = key.charCodeAt(i++);
                k1 ^= ((top & 0xff) << 24) ^
                      ((top & 0xff00) >> 8);
            }
 
            k1 = 0;
            switch (this.rem) {
                case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16;
                case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8;
                case 1: k1 ^= (key.charCodeAt(i) & 0xffff);
            }
 
            this.h1 = h1;
        }
 
        this.k1 = k1;
        return this;
    };
 
    // Get the result of this hash
    //
    // @return {number} The 32-bit hash
    MurmurHash3.prototype.result = function() {
        var k1, h1;
        
        k1 = this.k1;
        h1 = this.h1;
 
        if (k1 > 0) {
            k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff;
            k1 = (k1 << 15) | (k1 >>> 17);
            k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff;
            h1 ^= k1;
        }
 
        h1 ^= this.len;
 
        h1 ^= h1 >>> 16;
        h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff;
        h1 ^= h1 >>> 13;
        h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff;
        h1 ^= h1 >>> 16;
 
        return h1 >>> 0;
    };
 
    // Reset the hash object for reuse
    //
    // @param {number} seed An optional positive integer
    MurmurHash3.prototype.reset = function(seed) {
        this.h1 = typeof seed === 'number' ? seed : 0;
        this.rem = this.k1 = this.len = 0;
        return this;
    };
 
    // A cached object to use. This can be safely used if you're in a single-
    // threaded environment, otherwise you need to create new hashes to use.
    cache = new MurmurHash3();
 
    Eif (typeof(module) != 'undefined') {
        module.exports = MurmurHash3;
    } else {
        this.MurmurHash3 = MurmurHash3;
    }
}());
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inflight/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inflight/

Statements: 24.14% (7 / 29)      Branches: 0% (0 / 4)      Functions: 0% (0 / 5)      Lines: 25% (7 / 28)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/inflight/
File Statements Branches Functions Lines
inflight.js 24.14% (7 / 29) 0% (0 / 4) 0% (0 / 5) 25% (7 / 28)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inflight/inflight.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inflight/inflight.js

Statements: 24.14% (7 / 29)      Branches: 0% (0 / 4)      Functions: 0% (0 / 5)      Lines: 25% (7 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561 1 1   1   1                   1                                                             1                
var wrappy = require('wrappy')
var reqs = Object.create(null)
var once = require('once')
 
module.exports = wrappy(inflight)
 
function inflight (key, cb) {
  if (reqs[key]) {
    reqs[key].push(cb)
    return null
  } else {
    reqs[key] = [cb]
    return makeres(key)
  }
}
 
function makeres (key) {
  return once(function RES () {
    var cbs = reqs[key]
    var len = cbs.length
    var args = slice(arguments)
 
    // XXX It's somewhat ambiguous whether a new callback added in this
    // pass should be queued for later execution if something in the
    // list of callbacks throws, or if it should just be discarded.
    // However, it's such an edge case that it hardly matters, and either
    // choice is likely as surprising as the other.
    // As it happens, we do go ahead and schedule it for later execution.
    try {
      for (var i = 0; i < len; i++) {
        cbs[i].apply(null, args)
      }
    } finally {
      if (cbs.length > len) {
        // added more in the interim.
        // de-zalgo, just in case, but don't call again.
        cbs.splice(0, len)
        process.nextTick(function () {
          RES.apply(null, args)
        })
      } else {
        delete reqs[key]
      }
    }
  })
}
 
function slice (args) {
  var length = args.length
  var array = []
 
  for (var i = 0; i < length; i++) array[i] = args[i]
  return array
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inherits/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inherits/

Statements: 66.67% (4 / 6)      Branches: 50% (1 / 2)      Functions: 100% (0 / 0)      Lines: 80% (4 / 5)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/inherits/
File Statements Branches Functions Lines
inherits.js 66.67% (4 / 6) 50% (1 / 2) 100% (0 / 0) 80% (4 / 5)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inherits/inherits.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/inherits/inherits.js

Statements: 66.67% (4 / 6)      Branches: 50% (1 / 2)      Functions: 100% (0 / 0)      Lines: 80% (4 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 91 1 1 1          
try {
  var util = require('util');
  Iif (typeof util.inherits !== 'function') throw '';
  module.exports = util.inherits;
} catch (e) {
  module.exports = require('./inherits_browser.js');
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ini/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ini/

Statements: 11% (11 / 100)      Branches: 1.06% (1 / 94)      Functions: 0% (0 / 14)      Lines: 11.7% (11 / 94)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/ini/
File Statements Branches Functions Lines
ini.js 11% (11 / 100) 1.06% (1 / 94) 0% (0 / 14) 11.7% (11 / 94)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ini/ini.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/ini/ini.js

Statements: 11% (11 / 100)      Branches: 1.06% (1 / 94)      Functions: 0% (0 / 14)      Lines: 11.7% (11 / 94)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192  1 1   1 1   1   1                                                                                                   1                 1                                                                                                                                               1         1                     1                                                                      
 
exports.parse = exports.decode = decode
exports.stringify = exports.encode = encode
 
exports.safe = safe
exports.unsafe = unsafe
 
var eol = process.platform === "win32" ? "\r\n" : "\n"
 
function encode (obj, opt) {
  var children = []
    , out = ""
 
  if (typeof opt === "string") {
    opt = {
      section: opt,
      whitespace: false
    }
  } else {
    opt = opt || {}
    opt.whitespace = opt.whitespace === true
  }
 
  var separator = opt.whitespace ? " = " : "="
 
  Object.keys(obj).forEach(function (k, _, __) {
    var val = obj[k]
    if (val && Array.isArray(val)) {
        val.forEach(function(item) {
            out += safe(k + "[]") + separator + safe(item) + "\n"
        })
    }
    else if (val && typeof val === "object") {
      children.push(k)
    } else {
      out += safe(k) + separator + safe(val) + eol
    }
  })
 
  if (opt.section && out.length) {
    out = "[" + safe(opt.section) + "]" + eol + out
  }
 
  children.forEach(function (k, _, __) {
    var nk = dotSplit(k).join('\\.')
    var section = (opt.section ? opt.section + "." : "") + nk
    var child = encode(obj[k], {
      section: section,
      whitespace: opt.whitespace
    })
    if (out.length && child.length) {
      out += eol
    }
    out += child
  })
 
  return out
}
 
function dotSplit (str) {
  return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
         .replace(/\\\./g, '\u0001')
         .split(/\./).map(function (part) {
           return part.replace(/\1/g, '\\.')
                  .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001')
        })
}
 
function decode (str) {
  var out = {}
    , p = out
    , section = null
    , state = "START"
           // section     |key = value
    , re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i
    , lines = str.split(/[\r\n]+/g)
    , section = null
 
  lines.forEach(function (line, _, __) {
    if (!line || line.match(/^\s*[;#]/)) return
    var match = line.match(re)
    if (!match) return
    if (match[1] !== undefined) {
      section = unsafe(match[1])
      p = out[section] = out[section] || {}
      return
    }
    var key = unsafe(match[2])
      , value = match[3] ? unsafe((match[4] || "")) : true
    switch (value) {
      case 'true':
      case 'false':
      case 'null': value = JSON.parse(value)
    }
 
    // Convert keys with '[]' suffix to an array
    if (key.length > 2 && key.slice(-2) === "[]") {
        key = key.substring(0, key.length - 2)
        if (!p[key]) {
          p[key] = []
        }
        else if (!Array.isArray(p[key])) {
          p[key] = [p[key]]
        }
    }
 
    // safeguard against resetting a previously defined
    // array by accidentally forgetting the brackets
    if (Array.isArray(p[key])) {
      p[key].push(value)
    }
    else {
      p[key] = value
    }
  })
 
  // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
  // use a filter to return the keys that have to be deleted.
  Object.keys(out).filter(function (k, _, __) {
    if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k])) return false
    // see if the parent section is also an object.
    // if so, add it to that, and mark this one for deletion
    var parts = dotSplit(k)
      , p = out
      , l = parts.pop()
      , nl = l.replace(/\\\./g, '.')
    parts.forEach(function (part, _, __) {
      if (!p[part] || typeof p[part] !== "object") p[part] = {}
      p = p[part]
    })
    if (p === out && nl === l) return false
    p[nl] = out[k]
    return true
  }).forEach(function (del, _, __) {
    delete out[del]
  })
 
  return out
}
 
function isQuoted (val) {
  return (val.charAt(0) === "\"" && val.slice(-1) === "\"")
         || (val.charAt(0) === "'" && val.slice(-1) === "'")
}
 
function safe (val) {
  return ( typeof val !== "string"
         || val.match(/[=\r\n]/)
         || val.match(/^\[/)
         || (val.length > 1
             && isQuoted(val))
         || val !== val.trim() )
         ? JSON.stringify(val)
         : val.replace(/;/g, '\\;').replace(/#/g, "\\#")
}
 
function unsafe (val, doUnesc) {
  val = (val || "").trim()
  if (isQuoted(val)) {
    // remove the single quotes before calling JSON.parse
    if (val.charAt(0) === "'") {
      val = val.substr(1, val.length - 2);
    }
    try { val = JSON.parse(val) } catch (_) {}
  } else {
    // walk the val to find the first not-escaped ; character
    var esc = false
    var unesc = "";
    for (var i = 0, l = val.length; i < l; i++) {
      var c = val.charAt(i)
      if (esc) {
        if ("\\;#".indexOf(c) !== -1)
          unesc += c
        else
          unesc += "\\" + c
        esc = false
      } else if (";#".indexOf(c) !== -1) {
        break
      } else if (c === "\\") {
        esc = true
      } else {
        unesc += c
      }
    }
    if (esc)
      unesc += "\\"
    return unesc
  }
  return val
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/

Statements: 15.38% (14 / 91)      Branches: 0% (0 / 57)      Functions: 0% (0 / 16)      Lines: 16.47% (14 / 85)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/init-package-json/
File Statements Branches Functions Lines
init-package-json.js 15.38% (14 / 91) 0% (0 / 57) 0% (0 / 16) 16.47% (14 / 85)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/init-package-json.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/init-package-json.js

Statements: 15.38% (14 / 91)      Branches: 0% (0 / 57)      Functions: 0% (0 / 16)      Lines: 16.47% (14 / 85)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153  1 1   1 1 1   1 1 1         1   1             1                                                                                                                                                                   1                                                   1                 1                      
 
module.exports = init
module.exports.yes = yes
 
var PZ = require('promzard').PromZard
var path = require('path')
var def = require.resolve('./default-input.js')
 
var fs = require('fs')
var semver = require('semver')
var read = require('read')
 
// to validate the data object at the end as a worthwhile package
// and assign default values for things.
// readJson.extras(file, data, cb)
var readJson = require('read-package-json')
 
function yes (conf) {
  return !!(
    conf.get('yes') || conf.get('y') ||
    conf.get('force') || conf.get('f')
  )
}
 
function init (dir, input, config, cb) {
  if (typeof config === 'function')
    cb = config, config = {}
 
  // accept either a plain-jane object, or a config object
  // with a "get" method.
  if (typeof config.get !== 'function') {
    var data = config
    config = {
      get: function (k) {
        return data[k]
      },
      toJSON: function () {
        return data
      }
    }
  }
 
  var packageFile = path.resolve(dir, 'package.json')
  input = path.resolve(input)
  var pkg
  var ctx = { yes: yes(config) }
 
  var es = readJson.extraSet
  readJson.extraSet = es.filter(function (fn) {
    return fn.name !== 'authors' && fn.name !== 'mans'
  })
  readJson(packageFile, function (er, d) {
    readJson.extraSet = es
 
    if (er) pkg = {}
    else pkg = d
 
    ctx.filename = packageFile
    ctx.dirname = path.dirname(packageFile)
    ctx.basename = path.basename(ctx.dirname)
    if (!pkg.version || !semver.valid(pkg.version))
      delete pkg.version
 
    ctx.package = pkg
    ctx.config = config || {}
 
    // make sure that the input is valid.
    // if not, use the default
    var pz = new PZ(input, ctx)
    pz.backupFile = def
    pz.on('error', cb)
    pz.on('data', function (data) {
      Object.keys(data).forEach(function (k) {
        if (data[k] !== undefined && data[k] !== null) pkg[k] = data[k]
      })
 
      // only do a few of these.
      // no need for mans or contributors if they're in the files
      var es = readJson.extraSet
      readJson.extraSet = es.filter(function (fn) {
        return fn.name !== 'authors' && fn.name !== 'mans'
      })
      readJson.extras(packageFile, pkg, function (er, pkg) {
        readJson.extraSet = es
        if (er) return cb(er, pkg)
        pkg = unParsePeople(pkg)
        // no need for the readme now.
        delete pkg.readme
        delete pkg.readmeFilename
 
        // really don't want to have this lying around in the file
        delete pkg._id
 
        // ditto
        delete pkg.gitHead
 
        // if the repo is empty, remove it.
        if (!pkg.repository)
          delete pkg.repository
 
        // readJson filters out empty descriptions, but init-package-json
        // traditionally leaves them alone
        if (!pkg.description)
          pkg.description = data.description
 
        var d = JSON.stringify(pkg, null, 2) + '\n'
        function write (yes) {
          fs.writeFile(packageFile, d, 'utf8', function (er) {
            if (!er && yes && !config.get('silent')) {
              console.log('Wrote to %s:\n\n%s\n', packageFile, d)
            }
            return cb(er, pkg)
          })
        }
        if (ctx.yes) {
          return write(true)
        }
        console.log('About to write to %s:\n\n%s\n', packageFile, d)
        read({prompt:'Is this ok? ', default: 'yes'}, function (er, ok) {
          if (!ok || ok.toLowerCase().charAt(0) !== 'y') {
            console.log('Aborted.')
          } else {
            return write()
          }
        })
      })
    })
  })
 
}
 
// turn the objects into somewhat more humane strings.
function unParsePeople (data) {
  if (data.author) data.author = unParsePerson(data.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (!Array.isArray(data[set])) return;
    data[set] = data[set].map(unParsePerson)
  })
  return data
}
 
function unParsePerson (person) {
  if (typeof person === "string") return person
  var name = person.name || ""
  var u = person.url || person.web
  var url = u ? (" ("+u+")") : ""
  var e = person.email || person.mail
  var email = e ? (" <"+e+">") : ""
  return name+email+url
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/node_modules/promzard/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/node_modules/promzard/

Statements: 14.12% (24 / 170)      Branches: 0% (0 / 82)      Functions: 0% (0 / 23)      Lines: 14.72% (24 / 163)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/init-package-json/node_modules/promzard/
File Statements Branches Functions Lines
promzard.js 14.12% (24 / 170) 0% (0 / 82) 0% (0 / 23) 14.72% (24 / 163)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/node_modules/promzard/promzard.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/init-package-json/node_modules/promzard/promzard.js

Statements: 14.12% (24 / 170)      Branches: 0% (0 / 82)      Functions: 0% (0 / 23)      Lines: 14.72% (24 / 163)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 2401 1   1 1 1 1 1 1 1   1 1   1                 1                     1                   1                 1                                 1                                                               1                 1           1     1                                           1                           1                                                                                                                         1                                            
module.exports = promzard
promzard.PromZard = PromZard
 
var fs = require('fs')
var vm = require('vm')
var util = require('util')
var files = {}
var crypto = require('crypto')
var EventEmitter = require('events').EventEmitter
var read = require('read')
 
var Module = require('module').Module
var path = require('path')
 
function promzard (file, ctx, cb) {
  if (typeof ctx === 'function') cb = ctx, ctx = null;
  if (!ctx) ctx = {};
  var pz = new PromZard(file, ctx)
  pz.on('error', cb)
  pz.on('data', function (data) {
    cb(null, data)
  })
}
promzard.fromBuffer = function (buf, ctx, cb) {
  var filename = 0
  do {
    filename = '\0' + Math.random();
  } while (files[filename])
  files[filename] = buf
  var ret = promzard(filename, ctx, cb)
  delete files[filename]
  return ret
}
 
function PromZard (file, ctx) {
  if (!(this instanceof PromZard))
    return new PromZard(file, ctx)
  EventEmitter.call(this)
  this.file = file
  this.ctx = ctx
  this.unique = crypto.randomBytes(8).toString('hex')
  this.load()
}
 
PromZard.prototype = Object.create(
  EventEmitter.prototype,
  { constructor: {
      value: PromZard,
      readable: true,
      configurable: true,
      writable: true,
      enumerable: false } } )
 
PromZard.prototype.load = function () {
  if (files[this.file])
    return this.loaded()
 
  fs.readFile(this.file, 'utf8', function (er, d) {
    if (er && this.backupFile) {
      this.file = this.backupFile
      delete this.backupFile
      return this.load()
    }
    if (er)
      return this.emit('error', this.error = er)
    files[this.file] = d
    this.loaded()
  }.bind(this))
}
 
PromZard.prototype.loaded = function () {
  this.ctx.prompt = this.makePrompt()
  this.ctx.__filename = this.file
  this.ctx.__dirname = path.dirname(this.file)
  this.ctx.__basename = path.basename(this.file)
  var mod = this.ctx.module = this.makeModule()
  this.ctx.require = function (path) {
    return mod.require(path)
  }
  this.ctx.require.resolve = function(path) {
    return Module._resolveFilename(path, mod);
  }
  this.ctx.exports = mod.exports
 
  this.script = this.wrap(files[this.file])
  var fn = vm.runInThisContext(this.script, this.file)
  var args = Object.keys(this.ctx).map(function (k) {
    return this.ctx[k]
  }.bind(this))
  try { var res = fn.apply(this.ctx, args) }
  catch (er) { this.emit('error', er) }
  if (res &&
      typeof res === 'object' &&
      exports === mod.exports &&
      Object.keys(exports).length === 1) {
    this.result = res
  } else {
    this.result = mod.exports
  }
  this.walk()
}
 
PromZard.prototype.makeModule = function () {
  var mod = new Module(this.file, module)
  mod.loaded = true
  mod.filename = this.file
  mod.id = this.file
  mod.paths = Module._nodeModulePaths(path.dirname(this.file))
  return mod
}
 
PromZard.prototype.wrap = function (body) {
  var s = '(function( %s ) { %s\n })'
  var args = Object.keys(this.ctx).join(', ')
  return util.format(s, args, body)
}
 
PromZard.prototype.makePrompt = function () {
  this.prompts = []
  return prompt.bind(this)
  function prompt () {
    var p, d, t
    for (var i = 0; i < arguments.length; i++) {
      var a = arguments[i]
      if (typeof a === 'string' && p)
        d = a
      else if (typeof a === 'string')
        p = a
      else if (typeof a === 'function')
        t = a
      else if (a && typeof a === 'object') {
        p = a.prompt || p
        d = a.default || d
        t = a.transform || t
      }
    }
 
    try { return this.unique + '-' + this.prompts.length }
    finally { this.prompts.push([p, d, t]) }
  }
}
 
PromZard.prototype.walk = function (o, cb) {
  o = o || this.result
  cb = cb || function (er, res) {
    if (er)
      return this.emit('error', this.error = er)
    this.result = res
    return this.emit('data', res)
  }
  cb = cb.bind(this)
  var keys = Object.keys(o)
  var i = 0
  var len = keys.length
 
  L.call(this)
  function L () {
    if (this.error)
      return
    while (i < len) {
      var k = keys[i]
      var v = o[k]
      i++
 
      if (v && typeof v === 'object') {
        return this.walk(v, function (er, res) {
          if (er) return cb(er)
          o[k] = res
          L.call(this)
        }.bind(this))
      } else if (v &&
                 typeof v === 'string' &&
                 v.indexOf(this.unique) === 0) {
        var n = +v.substr(this.unique.length + 1)
        var prompt = this.prompts[n]
        if (isNaN(n) || !prompt)
          continue
 
        // default to the key
        if (undefined === prompt[0])
          prompt[0] = k
 
        // default to the ctx value, if there is one
        if (undefined === prompt[1])
          prompt[1] = this.ctx[k]
 
        return this.prompt(prompt, function (er, res) {
          if (er) {
            if (!er.notValid) {
              return this.emit('error', this.error = er);
            }
            console.log(er.message)
            i --
            return L.call(this)
          }
          o[k] = res
          L.call(this)
        }.bind(this))
      } else if (typeof v === 'function') {
        try { return v.call(this.ctx, function (er, res) {
          if (er)
            return this.emit('error', this.error = er)
          o[k] = res
          // back up so that we process this one again.
          // this is because it might return a prompt() call in the cb.
          i --
          L.call(this)
        }.bind(this)) }
        catch (er) { this.emit('error', er) }
      }
    }
    // made it to the end of the loop, maybe
    if (i >= len)
      return cb(null, o)
  }
}
 
PromZard.prototype.prompt = function (pdt, cb) {
  var prompt = pdt[0]
  var def = pdt[1]
  var tx = pdt[2]
 
  if (tx) {
    cb = function (cb) { return function (er, data) {
      try {
        var res = tx(data)
        if (!er && res instanceof Error && !!res.notValid) {
          return cb(res, null)
        }
        return cb(er, res)
      }
      catch (er) { this.emit('error', er) }
    }}(cb).bind(this)
  }
 
  read({ prompt: prompt + ':' , default: def }, cb)
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lazy-property/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lazy-property/

Statements: 25% (2 / 8)      Branches: 100% (0 / 0)      Functions: 0% (0 / 3)      Lines: 25% (2 / 8)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/lazy-property/
File Statements Branches Functions Lines
lazyProperty.js 25% (2 / 8) 100% (0 / 0) 0% (0 / 3) 25% (2 / 8)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lazy-property/lazyProperty.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lazy-property/lazyProperty.js

Statements: 25% (2 / 8)      Branches: 100% (0 / 0)      Functions: 0% (0 / 3)      Lines: 25% (2 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21    1                               1    
"use strict"
 
function addLazyProperty(object, name, initializer, enumerable) {
  Object.defineProperty(object, name, {
    get: function() {
      var v = initializer.call(this)
      Object.defineProperty(this, name, { value: v, enumerable: !!enumerable, writable: true })
      return v
    },
    set: function(v) {
      Object.defineProperty(this, name, { value: v, enumerable: !!enumerable, writable: true })
      return v
    },
    enumerable: !!enumerable,
    configurable: true
  })
}
 
module.exports = addLazyProperty
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lockfile/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lockfile/

Statements: 13.33% (26 / 195)      Branches: 4% (4 / 100)      Functions: 0% (0 / 32)      Lines: 14.77% (26 / 176)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/lockfile/
File Statements Branches Functions Lines
lockfile.js 13.33% (26 / 195) 4% (4 / 100) 0% (0 / 32) 14.77% (26 / 176)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lockfile/lockfile.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lockfile/lockfile.js

Statements: 13.33% (26 / 195)      Branches: 4% (4 / 100)      Functions: 0% (0 / 32)      Lines: 14.77% (26 / 176)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 3131   1 1         1 1 1       1 1 1 1                 1   1       1               1                               1             1                   1                                                       1                                                                 1 1                                       1                                                                               1                                                                           1                                     1           1                                                                                     1                      
var fs = require('fs')
 
var wx = 'wx'
Iif (process.version.match(/^v0\.[0-6]/)) {
  var c = require('constants')
  wx = c.O_TRUNC | c.O_CREAT | c.O_WRONLY | c.O_EXCL
}
 
var os = require('os')
exports.filetime = 'ctime'
Iif (os.platform() == "win32") {
  exports.filetime = 'mtime'
}
 
var debug
var util = require('util')
Eif (util.debuglog)
  debug = util.debuglog('LOCKFILE')
else if (/\blockfile\b/i.test(process.env.NODE_DEBUG))
  debug = function() {
    var msg = util.format.apply(util, arguments)
    console.error('LOCKFILE %d %s', process.pid, msg)
  }
else
  debug = function() {}
 
var locks = {}
 
function hasOwnProperty (obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop)
}
 
process.on('exit', function () {
  debug('exit listener')
  // cleanup
  Object.keys(locks).forEach(exports.unlockSync)
})
 
// XXX https://github.com/joyent/node/issues/3555
// Remove when node 0.8 is deprecated.
Iif (/^v0\.[0-8]\./.test(process.version)) {
  debug('uncaughtException, version = %s', process.version)
  process.on('uncaughtException', function H (er) {
    debug('uncaughtException')
    var l = process.listeners('uncaughtException').filter(function (h) {
      return h !== H
    })
    if (!l.length) {
      // cleanup
      try { Object.keys(locks).forEach(exports.unlockSync) } catch (e) {}
      process.removeListener('uncaughtException', H)
      throw er
    }
  })
}
 
exports.unlock = function (path, cb) {
  debug('unlock', path)
  // best-effort.  unlocking an already-unlocked lock is a noop
  delete locks[path]
  fs.unlink(path, function (unlinkEr) { cb && cb() })
}
 
exports.unlockSync = function (path) {
  debug('unlockSync', path)
  // best-effort.  unlocking an already-unlocked lock is a noop
  try { fs.unlinkSync(path) } catch (er) {}
  delete locks[path]
}
 
 
// if the file can be opened in readonly mode, then it's there.
// if the error is something other than ENOENT, then it's not.
exports.check = function (path, opts, cb) {
  if (typeof opts === 'function') cb = opts, opts = {}
  debug('check', path, opts)
  fs.open(path, 'r', function (er, fd) {
    if (er) {
      if (er.code !== 'ENOENT') return cb(er)
      return cb(null, false)
    }
 
    if (!opts.stale) {
      return fs.close(fd, function (er) {
        return cb(er, true)
      })
    }
 
    fs.fstat(fd, function (er, st) {
      if (er) return fs.close(fd, function (er2) {
        return cb(er)
      })
 
      fs.close(fd, function (er) {
        var age = Date.now() - st[exports.filetime].getTime()
        return cb(er, age <= opts.stale)
      })
    })
  })
}
 
exports.checkSync = function (path, opts) {
  opts = opts || {}
  debug('checkSync', path, opts)
  if (opts.wait) {
    throw new Error('opts.wait not supported sync for obvious reasons')
  }
 
  try {
    var fd = fs.openSync(path, 'r')
  } catch (er) {
    if (er.code !== 'ENOENT') throw er
    return false
  }
 
  if (!opts.stale) {
    try { fs.closeSync(fd) } catch (er) {}
    return true
  }
 
  // file exists.  however, might be stale
  if (opts.stale) {
    try {
      var st = fs.fstatSync(fd)
    } finally {
      fs.closeSync(fd)
    }
    var age = Date.now() - st[exports.filetime].getTime()
    return (age <= opts.stale)
  }
}
 
 
 
var req = 1
exports.lock = function (path, opts, cb) {
  if (typeof opts === 'function') cb = opts, opts = {}
  opts.req = opts.req || req++
  debug('lock', path, opts)
  opts.start = opts.start || Date.now()
 
  if (typeof opts.retries === 'number' && opts.retries > 0) {
    debug('has retries', opts.retries)
    var retries = opts.retries
    opts.retries = 0
    cb = (function (orig) { return function cb (er, fd) {
      debug('retry-mutated callback')
      retries -= 1
      if (!er || retries < 0) return orig(er, fd)
 
      debug('lock retry', path, opts)
 
      if (opts.retryWait) setTimeout(retry, opts.retryWait)
      else retry()
 
      function retry () {
        opts.start = Date.now()
        debug('retrying', opts.start)
        exports.lock(path, opts, cb)
      }
    }})(cb)
  }
 
  // try to engage the lock.
  // if this succeeds, then we're in business.
  fs.open(path, wx, function (er, fd) {
    if (!er) {
      debug('locked', path, fd)
      locks[path] = fd
      return fs.close(fd, function () {
        return cb()
      })
    }
 
    // something other than "currently locked"
    // maybe eperm or something.
    if (er.code !== 'EEXIST') return cb(er)
 
    // someone's got this one.  see if it's valid.
    if (!opts.stale) return notStale(er, path, opts, cb)
 
    return maybeStale(er, path, opts, false, cb)
  })
}
 
 
// Staleness checking algorithm
// 1. acquire $lock, fail
// 2. stat $lock, find that it is stale
// 3. acquire $lock.STALE
// 4. stat $lock, assert that it is still stale
// 5. unlink $lock
// 6. link $lock.STALE $lock
// 7. unlink $lock.STALE
// On any failure, clean up whatever we've done, and raise the error.
function maybeStale (originalEr, path, opts, hasStaleLock, cb) {
  fs.stat(path, function (statEr, st) {
    if (statEr) {
      if (statEr.code === 'ENOENT') {
        // expired already!
        opts.stale = false
        debug('lock stale enoent retry', path, opts)
        exports.lock(path, opts, cb)
        return
      }
      return cb(statEr)
    }
 
    var age = Date.now() - st[exports.filetime].getTime()
    if (age <= opts.stale) return notStale(originalEr, path, opts, cb)
 
    debug('lock stale', path, opts)
    if (hasStaleLock) {
      exports.unlock(path, function (er) {
        if (er) return cb(er)
        debug('lock stale retry', path, opts)
        fs.link(path + '.STALE', path, function (er) {
          fs.unlink(path + '.STALE', function () {
            // best effort.  if the unlink fails, oh well.
            cb(er)
          })
        })
      })
    } else {
      debug('acquire .STALE file lock', opts)
      exports.lock(path + '.STALE', opts, function (er) {
        if (er) return cb(er)
        maybeStale(originalEr, path, opts, true, cb)
      })
    }
  })
}
 
function notStale (er, path, opts, cb) {
  debug('notStale', path, opts)
 
  // if we can't wait, then just call it a failure
  if (typeof opts.wait !== 'number' || opts.wait <= 0)
    return cb(er)
 
  // poll for some ms for the lock to clear
  var now = Date.now()
  var start = opts.start || now
  var end = start + opts.wait
 
  if (end <= now)
    return cb(er)
 
  debug('now=%d, wait until %d (delta=%d)', start, end, end-start)
  var wait = Math.min(end - start, opts.pollPeriod || 100)
  var timer = setTimeout(poll, wait)
 
  function poll () {
    debug('notStale, polling', path, opts)
    exports.lock(path, opts, cb)
  }
}
 
exports.lockSync = function (path, opts) {
  opts = opts || {}
  opts.req = opts.req || req++
  debug('lockSync', path, opts)
  if (opts.wait || opts.retryWait) {
    throw new Error('opts.wait not supported sync for obvious reasons')
  }
 
  try {
    var fd = fs.openSync(path, wx)
    locks[path] = fd
    try { fs.closeSync(fd) } catch (er) {}
    debug('locked sync!', path, fd)
    return
  } catch (er) {
    if (er.code !== 'EEXIST') return retryThrow(path, opts, er)
 
    if (opts.stale) {
      var st = fs.statSync(path)
      var ct = st[exports.filetime].getTime()
      if (!(ct % 1000) && (opts.stale % 1000)) {
        // probably don't have subsecond resolution.
        // round up the staleness indicator.
        // Yes, this will be wrong 1/1000 times on platforms
        // with subsecond stat precision, but that's acceptable
        // in exchange for not mistakenly removing locks on
        // most other systems.
        opts.stale = 1000 * Math.ceil(opts.stale / 1000)
      }
      var age = Date.now() - ct
      if (age > opts.stale) {
        debug('lockSync stale', path, opts, age)
        exports.unlockSync(path)
        return exports.lockSync(path, opts)
      }
    }
 
    // failed to lock!
    debug('failed to lock', path, opts, er)
    return retryThrow(path, opts, er)
  }
}
 
function retryThrow (path, opts, er) {
  if (typeof opts.retries === 'number' && opts.retries > 0) {
    var newRT = opts.retries - 1
    debug('retryThrow', path, opts, newRT)
    opts.retries = newRT
    return exports.lockSync(path, opts)
  }
  throw er
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.clonedeep/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.clonedeep/

Statements: 38.35% (153 / 399)      Branches: 16.56% (51 / 308)      Functions: 11.76% (10 / 85)      Lines: 38.35% (153 / 399)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/lodash.clonedeep/
File Statements Branches Functions Lines
index.js 38.35% (153 / 399) 16.56% (51 / 308) 11.76% (10 / 85) 38.35% (153 / 399)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.clonedeep/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.clonedeep/index.js

Statements: 38.35% (153 / 399)      Branches: 16.56% (51 / 308)      Functions: 11.76% (10 / 85)      Lines: 38.35% (153 / 399)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750                    1     1     1     1                                 1                               1     1     1     1     1 1                     1       1     1     1     1     1     1                   1                           1                             1                                       1                                             1                                           1                                   1 6                   1                                     1                                   1 3                       1                     1         1     1 1 1       1     1             1     1           1                 1         1               1             1                   1                                   1                           1                         1                                   1                             1             1 1 1 1 1                 1                                   1                         1                                                 1                               1                           1                         1 1 1 1 1                 1                                   1                                 1                         1                         1                           1           1 1 1 1 1                 1                     1                         1                         1                         1                           1                             1 1 1 1 1                   1                                                         1                               1                                     1                                   1                                                                                                                                         1                             1                       1 5                     1 6     6 6                   1                                         1                               1                           1                           1                       1                             1                       1                       1                         1                                         1                                                   1                     1                       1                             1 6 6                   1                 1       1                                                           1                                     1                                     1                                                                                       1                           1                           1 6                   1                           1 11 11 11                                                     1                                                                       1                                           1                                                         1                                                     1                                                         1                                         1                                     1     6 6                                                         1                                                           1 12 12                                                     1                                                               1                                           1                                 1       1    
/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */
 
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
 
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
 
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
 
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]',
    weakMapTag = '[object WeakMap]';
 
var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';
 
/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
 
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
 
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
 
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
 
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
 
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
 
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
 
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
 
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
 
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
 
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
 
/**
 * Adds the key-value `pair` to `map`.
 *
 * @private
 * @param {Object} map The map to modify.
 * @param {Array} pair The key-value pair to add.
 * @returns {Object} Returns `map`.
 */
function addMapEntry(map, pair) {
  // Don't return `map.set` because it's not chainable in IE 11.
  map.set(pair[0], pair[1]);
  return map;
}
 
/**
 * Adds `value` to `set`.
 *
 * @private
 * @param {Object} set The set to modify.
 * @param {*} value The value to add.
 * @returns {Object} Returns `set`.
 */
function addSetEntry(set, value) {
  // Don't return `set.add` because it's not chainable in IE 11.
  set.add(value);
  return set;
}
 
/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
      length = array ? array.length : 0;
 
  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}
 
/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;
 
  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}
 
/**
 * A specialized version of `_.reduce` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @param {boolean} [initAccum] Specify using the first element of `array` as
 *  the initial value.
 * @returns {*} Returns the accumulated value.
 */
function arrayReduce(array, iteratee, accumulator, initAccum) {
  var index = -1,
      length = array ? array.length : 0;
 
  if (initAccum && length) {
    accumulator = array[++index];
  }
  while (++index < length) {
    accumulator = iteratee(accumulator, array[index], index, array);
  }
  return accumulator;
}
 
/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);
 
  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}
 
/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}
 
/**
 * Checks if `value` is a host object in IE < 9.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
 */
function isHostObject(value) {
  // Many host objects are `Object` objects that can coerce to strings
  // despite having improperly defined `toString` methods.
  var result = false;
  if (value != null && typeof value.toString != 'function') {
    try {
      result = !!(value + '');
    } catch (e) {}
  }
  return result;
}
 
/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
      result = Array(map.size);
 
  map.forEach(function(value, key) {
    result[++index] = [key, value];
  });
  return result;
}
 
/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}
 
/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);
 
  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}
 
/** Used for built-in method references. */
var arrayProto = Array.prototype,
    funcProto = Function.prototype,
    objectProto = Object.prototype;
 
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
 
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());
 
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
 
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
 
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;
 
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
 
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
    Symbol = root.Symbol,
    Uint8Array = root.Uint8Array,
    getPrototype = overArg(Object.getPrototypeOf, Object),
    objectCreate = Object.create,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    splice = arrayProto.splice;
 
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
    nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
    nativeKeys = overArg(Object.keys, Object);
 
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
    Map = getNative(root, 'Map'),
    Promise = getNative(root, 'Promise'),
    Set = getNative(root, 'Set'),
    WeakMap = getNative(root, 'WeakMap'),
    nativeCreate = getNative(Object, 'create');
 
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
    mapCtorString = toSource(Map),
    promiseCtorString = toSource(Promise),
    setCtorString = toSource(Set),
    weakMapCtorString = toSource(WeakMap);
 
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
 
/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
}
 
/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  return this.has(key) && delete this.__data__[key];
}
 
/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
 
/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
 
/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  return this;
}
 
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
 
/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
}
 
/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  return true;
}
 
/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  return index < 0 ? undefined : data[index][1];
}
 
/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}
 
/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  if (index < 0) {
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}
 
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
 
/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.__data__ = {
    'hash': new Hash,
    'map': new (Map || ListCache),
    'string': new Hash
  };
}
 
/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  return getMapData(this, key)['delete'](key);
}
 
/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}
 
/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}
 
/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  getMapData(this, key).set(key, value);
  return this;
}
 
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
 
/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  this.__data__ = new ListCache(entries);
}
 
/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new ListCache;
}
 
/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  return this.__data__['delete'](key);
}
 
/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}
 
/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}
 
/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet(key, value) {
  var cache = this.__data__;
  if (cache instanceof ListCache) {
    var pairs = cache.__data__;
    if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
      pairs.push([key, value]);
      return this;
    }
    cache = this.__data__ = new MapCache(pairs);
  }
  cache.set(key, value);
  return this;
}
 
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
 
/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys(value, inherited) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  // Safari 9 makes `arguments.length` enumerable in strict mode.
  var result = (isArray(value) || isArguments(value))
    ? baseTimes(value.length, String)
    : [];
 
  var length = result.length,
      skipIndexes = !!length;
 
  for (var key in value) {
    if ((inherited || hasOwnProperty.call(value, key)) &&
        !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
      result.push(key);
    }
  }
  return result;
}
 
/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignValue(object, key, value) {
  var objValue = object[key];
  if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
      (value === undefined && !(key in object))) {
    object[key] = value;
  }
}
 
/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}
 
/**
 * The base implementation of `_.assign` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function baseAssign(object, source) {
  return object && copyObject(source, keys(source), object);
}
 
/**
 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @param {boolean} [isFull] Specify a clone including symbols.
 * @param {Function} [customizer] The function to customize cloning.
 * @param {string} [key] The key of `value`.
 * @param {Object} [object] The parent object of `value`.
 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
 * @returns {*} Returns the cloned value.
 */
function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
  var result;
  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }
  if (result !== undefined) {
    return result;
  }
  if (!isObject(value)) {
    return value;
  }
  var isArr = isArray(value);
  if (isArr) {
    result = initCloneArray(value);
    if (!isDeep) {
      return copyArray(value, result);
    }
  } else {
    var tag = getTag(value),
        isFunc = tag == funcTag || tag == genTag;
 
    if (isBuffer(value)) {
      return cloneBuffer(value, isDeep);
    }
    if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
      if (isHostObject(value)) {
        return object ? value : {};
      }
      result = initCloneObject(isFunc ? {} : value);
      if (!isDeep) {
        return copySymbols(value, baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = initCloneByTag(value, tag, baseClone, isDeep);
    }
  }
  // Check for circular references and return its corresponding clone.
  stack || (stack = new Stack);
  var stacked = stack.get(value);
  if (stacked) {
    return stacked;
  }
  stack.set(value, result);
 
  if (!isArr) {
    var props = isFull ? getAllKeys(value) : keys(value);
  }
  arrayEach(props || value, function(subValue, key) {
    if (props) {
      key = subValue;
      subValue = value[key];
    }
    // Recursively populate clone (susceptible to call stack limits).
    assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
  });
  return result;
}
 
/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} prototype The object to inherit from.
 * @returns {Object} Returns the new object.
 */
function baseCreate(proto) {
  return isObject(proto) ? objectCreate(proto) : {};
}
 
/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
 
/**
 * The base implementation of `getTag`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  return objectToString.call(value);
}
 
/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  Iif (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}
 
/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys(object) {
  if (!isPrototype(object)) {
    return nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}
 
/**
 * Creates a clone of  `buffer`.
 *
 * @private
 * @param {Buffer} buffer The buffer to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Buffer} Returns the cloned buffer.
 */
function cloneBuffer(buffer, isDeep) {
  if (isDeep) {
    return buffer.slice();
  }
  var result = new buffer.constructor(buffer.length);
  buffer.copy(result);
  return result;
}
 
/**
 * Creates a clone of `arrayBuffer`.
 *
 * @private
 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
 * @returns {ArrayBuffer} Returns the cloned array buffer.
 */
function cloneArrayBuffer(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  return result;
}
 
/**
 * Creates a clone of `dataView`.
 *
 * @private
 * @param {Object} dataView The data view to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned data view.
 */
function cloneDataView(dataView, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
 
/**
 * Creates a clone of `map`.
 *
 * @private
 * @param {Object} map The map to clone.
 * @param {Function} cloneFunc The function to clone values.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned map.
 */
function cloneMap(map, isDeep, cloneFunc) {
  var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
  return arrayReduce(array, addMapEntry, new map.constructor);
}
 
/**
 * Creates a clone of `regexp`.
 *
 * @private
 * @param {Object} regexp The regexp to clone.
 * @returns {Object} Returns the cloned regexp.
 */
function cloneRegExp(regexp) {
  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}
 
/**
 * Creates a clone of `set`.
 *
 * @private
 * @param {Object} set The set to clone.
 * @param {Function} cloneFunc The function to clone values.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned set.
 */
function cloneSet(set, isDeep, cloneFunc) {
  var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
  return arrayReduce(array, addSetEntry, new set.constructor);
}
 
/**
 * Creates a clone of the `symbol` object.
 *
 * @private
 * @param {Object} symbol The symbol object to clone.
 * @returns {Object} Returns the cloned symbol object.
 */
function cloneSymbol(symbol) {
  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
 
/**
 * Creates a clone of `typedArray`.
 *
 * @private
 * @param {Object} typedArray The typed array to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned typed array.
 */
function cloneTypedArray(typedArray, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
 
/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
      length = source.length;
 
  array || (array = Array(length));
  while (++index < length) {
    array[index] = source[index];
  }
  return array;
}
 
/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */
function copyObject(source, props, object, customizer) {
  object || (object = {});
 
  var index = -1,
      length = props.length;
 
  while (++index < length) {
    var key = props[index];
 
    var newValue = customizer
      ? customizer(object[key], source[key], key, object, source)
      : undefined;
 
    assignValue(object, key, newValue === undefined ? source[key] : newValue);
  }
  return object;
}
 
/**
 * Copies own symbol properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function copySymbols(source, object) {
  return copyObject(source, getSymbols(source), object);
}
 
/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys(object) {
  return baseGetAllKeys(object, keys, getSymbols);
}
 
/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}
 
/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}
 
/**
 * Creates an array of the own enumerable symbol properties of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
 
/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag = baseGetTag;
 
// Fallback for data views, maps, sets, and weak maps in IE 11,
// for data views in Edge < 14, and promises in Node.js.
Iif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
    (Map && getTag(new Map) != mapTag) ||
    (Promise && getTag(Promise.resolve()) != promiseTag) ||
    (Set && getTag(new Set) != setTag) ||
    (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  getTag = function(value) {
    var result = objectToString.call(value),
        Ctor = result == objectTag ? value.constructor : undefined,
        ctorString = Ctor ? toSource(Ctor) : undefined;
 
    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString: return dataViewTag;
        case mapCtorString: return mapTag;
        case promiseCtorString: return promiseTag;
        case setCtorString: return setTag;
        case weakMapCtorString: return weakMapTag;
      }
    }
    return result;
  };
}
 
/**
 * Initializes an array clone.
 *
 * @private
 * @param {Array} array The array to clone.
 * @returns {Array} Returns the initialized clone.
 */
function initCloneArray(array) {
  var length = array.length,
      result = array.constructor(length);
 
  // Add properties assigned by `RegExp#exec`.
  if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
    result.index = array.index;
    result.input = array.input;
  }
  return result;
}
 
/**
 * Initializes an object clone.
 *
 * @private
 * @param {Object} object The object to clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneObject(object) {
  return (typeof object.constructor == 'function' && !isPrototype(object))
    ? baseCreate(getPrototype(object))
    : {};
}
 
/**
 * Initializes an object clone based on its `toStringTag`.
 *
 * **Note:** This function only supports cloning values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {Function} cloneFunc The function to clone values.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneByTag(object, tag, cloneFunc, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case arrayBufferTag:
      return cloneArrayBuffer(object);
 
    case boolTag:
    case dateTag:
      return new Ctor(+object);
 
    case dataViewTag:
      return cloneDataView(object, isDeep);
 
    case float32Tag: case float64Tag:
    case int8Tag: case int16Tag: case int32Tag:
    case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
      return cloneTypedArray(object, isDeep);
 
    case mapTag:
      return cloneMap(object, isDeep, cloneFunc);
 
    case numberTag:
    case stringTag:
      return new Ctor(object);
 
    case regexpTag:
      return cloneRegExp(object);
 
    case setTag:
      return cloneSet(object, isDeep, cloneFunc);
 
    case symbolTag:
      return cloneSymbol(object);
  }
}
 
/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length &&
    (typeof value == 'number' || reIsUint.test(value)) &&
    (value > -1 && value % 1 == 0 && value < length);
}
 
/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}
 
/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}
 
/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
 
  return value === proto;
}
 
/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to process.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  Eif (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}
 
/**
 * This method is like `_.clone` except that it recursively clones `value`.
 *
 * @static
 * @memberOf _
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see _.clone
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var deep = _.cloneDeep(objects);
 * console.log(deep[0] === objects[0]);
 * // => false
 */
function cloneDeep(value) {
  return baseClone(value, true, true);
}
 
/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}
 
/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
function isArguments(value) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
    (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
 
/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;
 
/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}
 
/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */
function isArrayLikeObject(value) {
  return isObjectLike(value) && isArrayLike(value);
}
 
/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var isBuffer = nativeIsBuffer || stubFalse;
 
/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}
 
/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
 
/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}
 
/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}
 
/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
 
/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}
 
/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}
 
module.exports = cloneDeep;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.union/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.union/

Statements: 40.86% (114 / 279)      Branches: 15.22% (28 / 184)      Functions: 19.3% (11 / 57)      Lines: 40.86% (114 / 279)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/lodash.union/
File Statements Branches Functions Lines
index.js 40.86% (114 / 279) 15.22% (28 / 184) 19.3% (11 / 57) 40.86% (114 / 279)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.union/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.union/index.js

Statements: 40.86% (114 / 279)      Branches: 15.22% (28 / 184)      Functions: 19.3% (11 / 57)      Lines: 40.86% (114 / 279)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183                    1     1     1       1               1     1     1     1     1                       1                                     1                           1                                       1                                           1                                         1                                           1                       1                       1 3                   1                                     1 1     1 2   1       1         1     1 1 1       1     1             1     1           1           1     1                     1                                   1                           1                         1                                   1                             1             1 1 1 1 1                 1                                   1                         1                                                 1                               1                           1                         1 1 1 1 1                 1                                   1                                 1                         1                         1                           1           1 1 1 1 1                   1                                       1                           1         1 1                   1                                         1                                                             1 3     3 3                     1 1 1                                                       1                                                                                                                     1                       1                             1 3 3                   1                       1                           1 3                   1 3 3 3                                                 1                                                                       1                                           1                                                         1                                                     1                                                         1                                         1     3 3                                                         1                                                           1 6 6                                                     1                               1       1    
/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */
 
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
 
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
 
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_SAFE_INTEGER = 9007199254740991;
 
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]';
 
/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
 
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
 
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
 
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
 
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
 
/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}
 
/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludes(array, value) {
  var length = array ? array.length : 0;
  return !!length && baseIndexOf(array, value, 0) > -1;
}
 
/**
 * This function is like `arrayIncludes` except that it accepts a comparator.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @param {Function} comparator The comparator invoked per element.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludesWith(array, value, comparator) {
  var index = -1,
      length = array ? array.length : 0;
 
  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }
  return false;
}
 
/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;
 
  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}
 
/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);
 
  while ((fromRight ? index-- : ++index < length)) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}
 
/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseIndexOf(array, value, fromIndex) {
  if (value !== value) {
    return baseFindIndex(array, baseIsNaN, fromIndex);
  }
  var index = fromIndex - 1,
      length = array.length;
 
  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}
 
/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}
 
/**
 * Checks if a cache value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}
 
/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}
 
/**
 * Checks if `value` is a host object in IE < 9.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
 */
function isHostObject(value) {
  // Many host objects are `Object` objects that can coerce to strings
  // despite having improperly defined `toString` methods.
  var result = false;
  if (value != null && typeof value.toString != 'function') {
    try {
      result = !!(value + '');
    } catch (e) {}
  }
  return result;
}
 
/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);
 
  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}
 
/** Used for built-in method references. */
var arrayProto = Array.prototype,
    funcProto = Function.prototype,
    objectProto = Object.prototype;
 
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
 
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());
 
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
 
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
 
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;
 
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
 
/** Built-in value references. */
var Symbol = root.Symbol,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    splice = arrayProto.splice,
    spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
 
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
 
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map'),
    Set = getNative(root, 'Set'),
    nativeCreate = getNative(Object, 'create');
 
/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
}
 
/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  return this.has(key) && delete this.__data__[key];
}
 
/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
 
/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
 
/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  return this;
}
 
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
 
/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
}
 
/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  return true;
}
 
/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  return index < 0 ? undefined : data[index][1];
}
 
/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}
 
/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  if (index < 0) {
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}
 
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
 
/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.__data__ = {
    'hash': new Hash,
    'map': new (Map || ListCache),
    'string': new Hash
  };
}
 
/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  return getMapData(this, key)['delete'](key);
}
 
/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}
 
/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}
 
/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  getMapData(this, key).set(key, value);
  return this;
}
 
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
 
/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache(values) {
  var index = -1,
      length = values ? values.length : 0;
 
  this.__data__ = new MapCache;
  while (++index < length) {
    this.add(values[index]);
  }
}
 
/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED);
  return this;
}
 
/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}
 
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
 
/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}
 
/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
      length = array.length;
 
  predicate || (predicate = isFlattenable);
  result || (result = []);
 
  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}
 
/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  Iif (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}
 
/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest(func, start) {
  start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  return function() {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);
 
    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = array;
    return apply(func, this, otherArgs);
  };
}
 
/**
 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns the new duplicate free array.
 */
function baseUniq(array, iteratee, comparator) {
  var index = -1,
      includes = arrayIncludes,
      length = array.length,
      isCommon = true,
      result = [],
      seen = result;
 
  if (comparator) {
    isCommon = false;
    includes = arrayIncludesWith;
  }
  else if (length >= LARGE_ARRAY_SIZE) {
    var set = iteratee ? null : createSet(array);
    if (set) {
      return setToArray(set);
    }
    isCommon = false;
    includes = cacheHas;
    seen = new SetCache;
  }
  else {
    seen = iteratee ? [] : result;
  }
  outer:
  while (++index < length) {
    var value = array[index],
        computed = iteratee ? iteratee(value) : value;
 
    value = (comparator || value !== 0) ? value : 0;
    if (isCommon && computed === computed) {
      var seenIndex = seen.length;
      while (seenIndex--) {
        if (seen[seenIndex] === computed) {
          continue outer;
        }
      }
      if (iteratee) {
        seen.push(computed);
      }
      result.push(value);
    }
    else if (!includes(seen, computed, comparator)) {
      if (seen !== result) {
        seen.push(computed);
      }
      result.push(value);
    }
  }
  return result;
}
 
/**
 * Creates a set object of `values`.
 *
 * @private
 * @param {Array} values The values to add to the set.
 * @returns {Object} Returns the new set.
 */
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
  return new Set(values);
};
 
/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}
 
/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}
 
/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */
function isFlattenable(value) {
  return isArray(value) || isArguments(value) ||
    !!(spreadableSymbol && value && value[spreadableSymbol]);
}
 
/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}
 
/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}
 
/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to process.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  Eif (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}
 
/**
 * Creates an array of unique values, in order, from all given arrays using
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {...Array} [arrays] The arrays to inspect.
 * @returns {Array} Returns the new array of combined values.
 * @example
 *
 * _.union([2], [1, 2]);
 * // => [2, 1]
 */
var union = baseRest(function(arrays) {
  return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
});
 
/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}
 
/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
function isArguments(value) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
    (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
 
/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;
 
/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}
 
/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */
function isArrayLikeObject(value) {
  return isObjectLike(value) && isArrayLike(value);
}
 
/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}
 
/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
 
/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}
 
/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}
 
/**
 * This method returns `undefined`.
 *
 * @static
 * @memberOf _
 * @since 2.3.0
 * @category Util
 * @example
 *
 * _.times(2, _.noop);
 * // => [undefined, undefined]
 */
function noop() {
  // No operation performed.
}
 
module.exports = union;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.without/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.without/

Statements: 41.27% (104 / 252)      Branches: 15.58% (24 / 154)      Functions: 17.31% (9 / 52)      Lines: 41.27% (104 / 252)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/lodash.without/
File Statements Branches Functions Lines
index.js 41.27% (104 / 252) 15.58% (24 / 154) 17.31% (9 / 52) 41.27% (104 / 252)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.without/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/lodash.without/index.js

Statements: 41.27% (104 / 252)      Branches: 15.58% (24 / 154)      Functions: 17.31% (9 / 52)      Lines: 41.27% (104 / 252)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053                    1     1     1     1             1     1     1     1     1                       1                                     1                           1                                         1                                           1                                         1                                           1                     1                           1                       1 2                   1                         1         1     1 1 1       1     1             1     1           1     1     1                   1                                   1                           1                         1                                   1                             1             1 1 1 1 1                 1                                   1                         1                                                 1                               1                           1                         1 1 1 1 1                 1                                   1                                 1                         1                         1                           1           1 1 1 1 1                   1                                       1                           1         1 1                   1                                         1                                                                                                         1 2     2 2                     1 1 1                                                     1                             1 2 2                   1                           1 2                   1 2 2 2                                                         1                                                                           1                                                         1                                                         1                                         1     2 2                                                         1                                                           1 4 4                                                     1       1    
/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */
 
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
 
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
 
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
 
/** `Object#toString` result references. */
var funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]';
 
/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
 
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
 
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
 
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
 
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
 
/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}
 
/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludes(array, value) {
  var length = array ? array.length : 0;
  return !!length && baseIndexOf(array, value, 0) > -1;
}
 
/**
 * This function is like `arrayIncludes` except that it accepts a comparator.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @param {Function} comparator The comparator invoked per element.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludesWith(array, value, comparator) {
  var index = -1,
      length = array ? array.length : 0;
 
  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }
  return false;
}
 
/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
      length = array ? array.length : 0,
      result = Array(length);
 
  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}
 
/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);
 
  while ((fromRight ? index-- : ++index < length)) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}
 
/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseIndexOf(array, value, fromIndex) {
  if (value !== value) {
    return baseFindIndex(array, baseIsNaN, fromIndex);
  }
  var index = fromIndex - 1,
      length = array.length;
 
  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}
 
/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}
 
/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function(value) {
    return func(value);
  };
}
 
/**
 * Checks if a cache value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}
 
/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}
 
/**
 * Checks if `value` is a host object in IE < 9.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
 */
function isHostObject(value) {
  // Many host objects are `Object` objects that can coerce to strings
  // despite having improperly defined `toString` methods.
  var result = false;
  if (value != null && typeof value.toString != 'function') {
    try {
      result = !!(value + '');
    } catch (e) {}
  }
  return result;
}
 
/** Used for built-in method references. */
var arrayProto = Array.prototype,
    funcProto = Function.prototype,
    objectProto = Object.prototype;
 
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
 
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());
 
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
 
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
 
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;
 
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
 
/** Built-in value references. */
var splice = arrayProto.splice;
 
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
 
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map'),
    nativeCreate = getNative(Object, 'create');
 
/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
}
 
/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  return this.has(key) && delete this.__data__[key];
}
 
/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
 
/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
 
/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  return this;
}
 
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
 
/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
}
 
/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  return true;
}
 
/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  return index < 0 ? undefined : data[index][1];
}
 
/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}
 
/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
 
  if (index < 0) {
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}
 
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
 
/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
      length = entries ? entries.length : 0;
 
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
 
/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.__data__ = {
    'hash': new Hash,
    'map': new (Map || ListCache),
    'string': new Hash
  };
}
 
/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  return getMapData(this, key)['delete'](key);
}
 
/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}
 
/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}
 
/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  getMapData(this, key).set(key, value);
  return this;
}
 
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
 
/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache(values) {
  var index = -1,
      length = values ? values.length : 0;
 
  this.__data__ = new MapCache;
  while (++index < length) {
    this.add(values[index]);
  }
}
 
/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED);
  return this;
}
 
/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}
 
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
 
/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}
 
/**
 * The base implementation of methods like `_.difference` without support
 * for excluding multiple arrays or iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Array} values The values to exclude.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns the new array of filtered values.
 */
function baseDifference(array, values, iteratee, comparator) {
  var index = -1,
      includes = arrayIncludes,
      isCommon = true,
      length = array.length,
      result = [],
      valuesLength = values.length;
 
  if (!length) {
    return result;
  }
  if (iteratee) {
    values = arrayMap(values, baseUnary(iteratee));
  }
  if (comparator) {
    includes = arrayIncludesWith;
    isCommon = false;
  }
  else if (values.length >= LARGE_ARRAY_SIZE) {
    includes = cacheHas;
    isCommon = false;
    values = new SetCache(values);
  }
  outer:
  while (++index < length) {
    var value = array[index],
        computed = iteratee ? iteratee(value) : value;
 
    value = (comparator || value !== 0) ? value : 0;
    if (isCommon && computed === computed) {
      var valuesIndex = valuesLength;
      while (valuesIndex--) {
        if (values[valuesIndex] === computed) {
          continue outer;
        }
      }
      result.push(value);
    }
    else if (!includes(values, computed, comparator)) {
      result.push(value);
    }
  }
  return result;
}
 
/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  Iif (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}
 
/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest(func, start) {
  start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  return function() {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);
 
    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = array;
    return apply(func, this, otherArgs);
  };
}
 
/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}
 
/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}
 
/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}
 
/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}
 
/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to process.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  Eif (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}
 
/**
 * Creates an array excluding all given values using
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * **Note:** Unlike `_.pull`, this method returns a new array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {...*} [values] The values to exclude.
 * @returns {Array} Returns the new array of filtered values.
 * @see _.difference, _.xor
 * @example
 *
 * _.without([2, 1, 2, 3], 1, 2);
 * // => [3]
 */
var without = baseRest(function(array, values) {
  return isArrayLikeObject(array)
    ? baseDifference(array, values)
    : [];
});
 
/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}
 
/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}
 
/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */
function isArrayLikeObject(value) {
  return isObjectLike(value) && isArrayLike(value);
}
 
/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}
 
/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
 
/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}
 
/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}
 
module.exports = without;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/

Statements: 100% (9 / 9)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (9 / 9)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/
File Statements Branches Functions Lines
index.js 100% (9 / 9) 100% (0 / 0) 100% (0 / 0) 100% (9 / 9)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/index.js

Statements: 100% (9 / 9)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (9 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 111 1 1 1 1 1 1 1 1    
module.exports.pipe = require('pump')
module.exports.each = require('stream-each')
module.exports.pipeline = require('pumpify')
module.exports.duplex = require('duplexify')
module.exports.through = require('through2')
module.exports.concat = require('concat-stream')
module.exports.finished = require('end-of-stream')
module.exports.from = require('from2')
module.exports.to = require('flush-write-stream')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/concat-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/concat-stream/

Statements: 15.6% (17 / 109)      Branches: 3.13% (2 / 64)      Functions: 0% (0 / 12)      Lines: 18.09% (17 / 94)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/concat-stream/
File Statements Branches Functions Lines
index.js 15.6% (17 / 109) 3.13% (2 / 64) 0% (0 / 12) 18.09% (17 / 94)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/concat-stream/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/concat-stream/index.js

Statements: 15.6% (17 / 109)      Branches: 3.13% (2 / 64)      Functions: 0% (0 / 12)      Lines: 18.09% (17 / 94)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 1451 1   1     1     1                                                           1 1   1         1                   1                   1       1       1       1                                               1                             1               1                                    
var Writable = require('readable-stream').Writable
var inherits = require('inherits')
 
Iif (typeof Uint8Array === 'undefined') {
  var U8 = require('typedarray').Uint8Array
} else {
  var U8 = Uint8Array
}
 
function ConcatStream(opts, cb) {
  if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb)
 
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }
  if (!opts) opts = {}
 
  var encoding = opts.encoding
  var shouldInferEncoding = false
 
  if (!encoding) {
    shouldInferEncoding = true
  } else {
    encoding =  String(encoding).toLowerCase()
    if (encoding === 'u8' || encoding === 'uint8') {
      encoding = 'uint8array'
    }
  }
 
  Writable.call(this, { objectMode: true })
 
  this.encoding = encoding
  this.shouldInferEncoding = shouldInferEncoding
 
  if (cb) this.on('finish', function () { cb(this.getBody()) })
  this.body = []
}
 
module.exports = ConcatStream
inherits(ConcatStream, Writable)
 
ConcatStream.prototype._write = function(chunk, enc, next) {
  this.body.push(chunk)
  next()
}
 
ConcatStream.prototype.inferEncoding = function (buff) {
  var firstBuffer = buff === undefined ? this.body[0] : buff;
  if (Buffer.isBuffer(firstBuffer)) return 'buffer'
  if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array'
  if (Array.isArray(firstBuffer)) return 'array'
  if (typeof firstBuffer === 'string') return 'string'
  if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object'
  return 'buffer'
}
 
ConcatStream.prototype.getBody = function () {
  if (!this.encoding && this.body.length === 0) return []
  if (this.shouldInferEncoding) this.encoding = this.inferEncoding()
  if (this.encoding === 'array') return arrayConcat(this.body)
  if (this.encoding === 'string') return stringConcat(this.body)
  if (this.encoding === 'buffer') return bufferConcat(this.body)
  if (this.encoding === 'uint8array') return u8Concat(this.body)
  return this.body
}
 
var isArray = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]'
}
 
function isArrayish (arr) {
  return /Array\]$/.test(Object.prototype.toString.call(arr))
}
 
function isBufferish (p) {
  return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function')
}
 
function stringConcat (parts) {
  var strings = []
  var needsToString = false
  for (var i = 0; i < parts.length; i++) {
    var p = parts[i]
    if (typeof p === 'string') {
      strings.push(p)
    } else if (Buffer.isBuffer(p)) {
      strings.push(p)
    } else if (isBufferish(p)) {
      strings.push(new Buffer(p))
    } else {
      strings.push(new Buffer(String(p)))
    }
  }
  if (Buffer.isBuffer(parts[0])) {
    strings = Buffer.concat(strings)
    strings = strings.toString('utf8')
  } else {
    strings = strings.join('')
  }
  return strings
}
 
function bufferConcat (parts) {
  var bufs = []
  for (var i = 0; i < parts.length; i++) {
    var p = parts[i]
    if (Buffer.isBuffer(p)) {
      bufs.push(p)
    } else if (isBufferish(p)) {
      bufs.push(new Buffer(p))
    } else {
      bufs.push(new Buffer(String(p)))
    }
  }
  return Buffer.concat(bufs)
}
 
function arrayConcat (parts) {
  var res = []
  for (var i = 0; i < parts.length; i++) {
    res.push.apply(res, parts[i])
  }
  return res
}
 
function u8Concat (parts) {
  var len = 0
  for (var i = 0; i < parts.length; i++) {
    if (typeof parts[i] === 'string') {
      parts[i] = new Buffer(parts[i])
    }
    len += parts[i].length
  }
  var u8 = new U8(len)
  for (var i = 0, offset = 0; i < parts.length; i++) {
    var part = parts[i]
    for (var j = 0; j < part.length; j++) {
      u8[offset++] = part[j]
    }
  }
  return u8
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/

Statements: 13.33% (24 / 180)      Branches: 0% (0 / 113)      Functions: 0% (0 / 26)      Lines: 16.44% (24 / 146)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/
File Statements Branches Functions Lines
index.js 13.33% (24 / 180) 0% (0 / 113) 0% (0 / 26) 16.44% (24 / 146)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/index.js

Statements: 13.33% (24 / 180)      Branches: 0% (0 / 113)      Functions: 0% (0 / 26)      Lines: 16.44% (24 / 146)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 2301 1 1 1   1   1         1             1               1       1                                               1   1             1       1       1                                                                       1                                                                                 1         1                           1                   1                               1                     1                         1                 1    
var stream = require('readable-stream')
var eos = require('end-of-stream')
var inherits = require('inherits')
var shift = require('stream-shift')
 
var SIGNAL_FLUSH = new Buffer([0])
 
var onuncork = function(self, fn) {
  if (self._corked) self.once('uncork', fn)
  else fn()
}
 
var destroyer = function(self, end) {
  return function(err) {
    if (err) self.destroy(err.message === 'premature close' ? null : err)
    else if (end && !self._ended) self.end()
  }
}
 
var end = function(ws, fn) {
  if (!ws) return fn()
  if (ws._writableState && ws._writableState.finished) return fn()
  if (ws._writableState) return ws.end(fn)
  ws.end()
  fn()
}
 
var toStreams2 = function(rs) {
  return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
}
 
var Duplexify = function(writable, readable, opts) {
  if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  stream.Duplex.call(this, opts)
 
  this._writable = null
  this._readable = null
  this._readable2 = null
 
  this._forwardDestroy = !opts || opts.destroy !== false
  this._forwardEnd = !opts || opts.end !== false
  this._corked = 1 // start corked
  this._ondrain = null
  this._drained = false
  this._forwarding = false
  this._unwrite = null
  this._unread = null
  this._ended = false
 
  this.destroyed = false
 
  if (writable) this.setWritable(writable)
  if (readable) this.setReadable(readable)
}
 
inherits(Duplexify, stream.Duplex)
 
Duplexify.obj = function(writable, readable, opts) {
  if (!opts) opts = {}
  opts.objectMode = true
  opts.highWaterMark = 16
  return new Duplexify(writable, readable, opts)
}
 
Duplexify.prototype.cork = function() {
  if (++this._corked === 1) this.emit('cork')
}
 
Duplexify.prototype.uncork = function() {
  if (this._corked && --this._corked === 0) this.emit('uncork')
}
 
Duplexify.prototype.setWritable = function(writable) {
  if (this._unwrite) this._unwrite()
 
  if (this.destroyed) {
    if (writable && writable.destroy) writable.destroy()
    return
  }
 
  if (writable === null || writable === false) {
    this.end()
    return
  }
 
  var self = this
  var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
 
  var ondrain = function() {
    var ondrain = self._ondrain
    self._ondrain = null
    if (ondrain) ondrain()
  }
 
  var clear = function() {
    self._writable.removeListener('drain', ondrain)
    unend()
  }
 
  if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
 
  this._writable = writable
  this._writable.on('drain', ondrain)
  this._unwrite = clear
 
  this.uncork() // always uncork setWritable
}
 
Duplexify.prototype.setReadable = function(readable) {
  if (this._unread) this._unread()
 
  if (this.destroyed) {
    if (readable && readable.destroy) readable.destroy()
    return
  }
 
  if (readable === null || readable === false) {
    this.push(null)
    this.resume()
    return
  }
 
  var self = this
  var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
 
  var onreadable = function() {
    self._forward()
  }
 
  var onend = function() {
    self.push(null)
  }
 
  var clear = function() {
    self._readable2.removeListener('readable', onreadable)
    self._readable2.removeListener('end', onend)
    unend()
  }
 
  this._drained = true
  this._readable = readable
  this._readable2 = readable._readableState ? readable : toStreams2(readable)
  this._readable2.on('readable', onreadable)
  this._readable2.on('end', onend)
  this._unread = clear
 
  this._forward()
}
 
Duplexify.prototype._read = function() {
  this._drained = true
  this._forward()
}
 
Duplexify.prototype._forward = function() {
  if (this._forwarding || !this._readable2 || !this._drained) return
  this._forwarding = true
 
  var data
 
  while (this._drained && (data = shift(this._readable2)) !== null) {
    if (this.destroyed) continue
    this._drained = this.push(data)
  }
 
  this._forwarding = false
}
 
Duplexify.prototype.destroy = function(err) {
  if (this.destroyed) return
  this.destroyed = true
 
  var self = this
  process.nextTick(function() {
    self._destroy(err)
  })
}
 
Duplexify.prototype._destroy = function(err) {
  if (err) {
    var ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain(err)
    else this.emit('error', err)
  }
 
  if (this._forwardDestroy) {
    if (this._readable && this._readable.destroy) this._readable.destroy()
    if (this._writable && this._writable.destroy) this._writable.destroy()
  }
 
  this.emit('close')
}
 
Duplexify.prototype._write = function(data, enc, cb) {
  if (this.destroyed) return cb()
  if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  if (data === SIGNAL_FLUSH) return this._finish(cb)
  if (!this._writable) return cb()
 
  if (this._writable.write(data) === false) this._ondrain = cb
  else cb()
}
 
 
Duplexify.prototype._finish = function(cb) {
  var self = this
  this.emit('preend')
  onuncork(this, function() {
    end(self._forwardEnd && self._writable, function() {
      // haxx to not emit prefinish twice
      if (self._writableState.prefinished === false) self._writableState.prefinished = true
      self.emit('prefinish')
      onuncork(self, cb)
    })
  })
}
 
Duplexify.prototype.end = function(data, enc, cb) {
  if (typeof data === 'function') return this.end(null, null, data)
  if (typeof enc === 'function') return this.end(data, null, enc)
  this._ended = true
  if (data) this.write(data)
  if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  return stream.Writable.prototype.end.call(this, cb)
}
 
module.exports = Duplexify
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/

Statements: 8.47% (5 / 59)      Branches: 0% (0 / 44)      Functions: 0% (0 / 9)      Lines: 10.2% (5 / 49)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/
File Statements Branches Functions Lines
index.js 8.47% (5 / 59) 0% (0 / 44) 0% (0 / 9) 10.2% (5 / 49)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/index.js

Statements: 8.47% (5 / 59)      Branches: 0% (0 / 44)      Functions: 0% (0 / 9)      Lines: 10.2% (5 / 49)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 731   1   1       1                                                                                                                             1  
var once = require('once');
 
var noop = function() {};
 
var isRequest = function(stream) {
	return stream.setHeader && typeof stream.abort === 'function';
};
 
var eos = function(stream, opts, callback) {
	if (typeof opts === 'function') return eos(stream, null, opts);
	if (!opts) opts = {};
 
	callback = once(callback || noop);
 
	var ws = stream._writableState;
	var rs = stream._readableState;
	var readable = opts.readable || (opts.readable !== false && stream.readable);
	var writable = opts.writable || (opts.writable !== false && stream.writable);
 
	var onlegacyfinish = function() {
		if (!stream.writable) onfinish();
	};
 
	var onfinish = function() {
		writable = false;
		if (!readable) callback();
	};
 
	var onend = function() {
		readable = false;
		if (!writable) callback();
	};
 
	var onclose = function() {
		if (readable && !(rs && rs.ended)) return callback(new Error('premature close'));
		if (writable && !(ws && ws.ended)) return callback(new Error('premature close'));
	};
 
	var onrequest = function() {
		stream.req.on('finish', onfinish);
	};
 
	if (isRequest(stream)) {
		stream.on('complete', onfinish);
		stream.on('abort', onclose);
		if (stream.req) onrequest();
		else stream.on('request', onrequest);
	} else if (writable && !ws) { // legacy streams
		stream.on('end', onlegacyfinish);
		stream.on('close', onlegacyfinish);
	}
 
	stream.on('end', onend);
	stream.on('finish', onfinish);
	if (opts.error !== false) stream.on('error', callback);
	stream.on('close', onclose);
 
	return function() {
		stream.removeListener('complete', onfinish);
		stream.removeListener('abort', onclose);
		stream.removeListener('request', onrequest);
		if (stream.req) stream.req.removeListener('finish', onfinish);
		stream.removeListener('end', onlegacyfinish);
		stream.removeListener('close', onlegacyfinish);
		stream.removeListener('finish', onfinish);
		stream.removeListener('end', onend);
		stream.removeListener('error', callback);
		stream.removeListener('close', onclose);
	};
};
 
module.exports = eos;
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/node_modules/once/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/node_modules/once/

Statements: 53.85% (7 / 13)      Branches: 0% (0 / 2)      Functions: 25% (1 / 4)      Lines: 58.33% (7 / 12)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/node_modules/once/
File Statements Branches Functions Lines
once.js 53.85% (7 / 13) 0% (0 / 2) 25% (1 / 4) 58.33% (7 / 12)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/node_modules/once/once.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/end-of-stream/node_modules/once/once.js

Statements: 53.85% (7 / 13)      Branches: 0% (0 / 2)      Functions: 25% (1 / 4)      Lines: 58.33% (7 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 231 1   1                 1 1         1 1      
var wrappy = require('wrappy')
module.exports = wrappy(once)
 
once.proto = once(function () {
  Object.defineProperty(Function.prototype, 'once', {
    value: function () {
      return once(this)
    },
    configurable: true
  })
})
 
function once (fn) {
  var f = function () {
    if (f.called) return f.value
    f.called = true
    return f.value = fn.apply(this, arguments)
  }
  f.called = false
  return f
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/stream-shift/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/stream-shift/

Statements: 25% (3 / 12)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 27.27% (3 / 11)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/stream-shift/
File Statements Branches Functions Lines
index.js 25% (3 / 12) 0% (0 / 8) 0% (0 / 2) 27.27% (3 / 11)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/stream-shift/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/duplexify/node_modules/stream-shift/index.js

Statements: 25% (3 / 12)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 27.27% (3 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 221   1           1                          
module.exports = shift
 
function shift (stream) {
  var rs = stream._readableState
  if (!rs) return null
  return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
}
 
function getStateLength (state) {
  if (state.buffer.length) {
    // Since node 6.3.0 state.buffer is a BufferList not an array
    if (state.buffer.head) {
      return state.buffer.head.data.length
    }
 
    return state.buffer[0].length
  }
 
  return state.length
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/

Statements: 9.09% (6 / 66)      Branches: 0% (0 / 51)      Functions: 0% (0 / 11)      Lines: 10.91% (6 / 55)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/
File Statements Branches Functions Lines
index.js 9.09% (6 / 66) 0% (0 / 51) 0% (0 / 11) 10.91% (6 / 55)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/index.js

Statements: 9.09% (6 / 66)      Branches: 0% (0 / 51)      Functions: 0% (0 / 11)      Lines: 10.91% (6 / 55)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 841   1   1       1       1                                                                                                                                           1  
var once = require('once');
 
var noop = function() {};
 
var isRequest = function(stream) {
	return stream.setHeader && typeof stream.abort === 'function';
};
 
var isChildProcess = function(stream) {
	return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
};
 
var eos = function(stream, opts, callback) {
	if (typeof opts === 'function') return eos(stream, null, opts);
	if (!opts) opts = {};
 
	callback = once(callback || noop);
 
	var ws = stream._writableState;
	var rs = stream._readableState;
	var readable = opts.readable || (opts.readable !== false && stream.readable);
	var writable = opts.writable || (opts.writable !== false && stream.writable);
 
	var onlegacyfinish = function() {
		if (!stream.writable) onfinish();
	};
 
	var onfinish = function() {
		writable = false;
		if (!readable) callback();
	};
 
	var onend = function() {
		readable = false;
		if (!writable) callback();
	};
 
	var onexit = function(exitCode) {
		callback(exitCode ? new Error('exited with error code: ' + exitCode) : null);
	};
 
	var onclose = function() {
		if (readable && !(rs && rs.ended)) return callback(new Error('premature close'));
		if (writable && !(ws && ws.ended)) return callback(new Error('premature close'));
	};
 
	var onrequest = function() {
		stream.req.on('finish', onfinish);
	};
 
	if (isRequest(stream)) {
		stream.on('complete', onfinish);
		stream.on('abort', onclose);
		if (stream.req) onrequest();
		else stream.on('request', onrequest);
	} else if (writable && !ws) { // legacy streams
		stream.on('end', onlegacyfinish);
		stream.on('close', onlegacyfinish);
	}
 
	if (isChildProcess(stream)) stream.on('exit', onexit);
 
	stream.on('end', onend);
	stream.on('finish', onfinish);
	if (opts.error !== false) stream.on('error', callback);
	stream.on('close', onclose);
 
	return function() {
		stream.removeListener('complete', onfinish);
		stream.removeListener('abort', onclose);
		stream.removeListener('request', onrequest);
		if (stream.req) stream.req.removeListener('finish', onfinish);
		stream.removeListener('end', onlegacyfinish);
		stream.removeListener('close', onlegacyfinish);
		stream.removeListener('finish', onfinish);
		stream.removeListener('exit', onexit);
		stream.removeListener('end', onend);
		stream.removeListener('error', callback);
		stream.removeListener('close', onclose);
	};
};
 
module.exports = eos;
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/node_modules/once/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/node_modules/once/

Statements: 53.85% (7 / 13)      Branches: 0% (0 / 2)      Functions: 25% (1 / 4)      Lines: 58.33% (7 / 12)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/node_modules/once/
File Statements Branches Functions Lines
once.js 53.85% (7 / 13) 0% (0 / 2) 25% (1 / 4) 58.33% (7 / 12)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/node_modules/once/once.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/end-of-stream/node_modules/once/once.js

Statements: 53.85% (7 / 13)      Branches: 0% (0 / 2)      Functions: 25% (1 / 4)      Lines: 58.33% (7 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 231 1   1                 1 1         1 1      
var wrappy = require('wrappy')
module.exports = wrappy(once)
 
once.proto = once(function () {
  Object.defineProperty(Function.prototype, 'once', {
    value: function () {
      return once(this)
    },
    configurable: true
  })
})
 
function once (fn) {
  var f = function () {
    if (f.called) return f.value
    f.called = true
    return f.value = fn.apply(this, arguments)
  }
  f.called = false
  return f
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/flush-write-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/flush-write-stream/

Statements: 21.74% (10 / 46)      Branches: 0% (0 / 28)      Functions: 0% (0 / 5)      Lines: 28.57% (10 / 35)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/flush-write-stream/
File Statements Branches Functions Lines
index.js 21.74% (10 / 46) 0% (0 / 28) 0% (0 / 5) 28.57% (10 / 35)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/flush-write-stream/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/flush-write-stream/index.js

Statements: 21.74% (10 / 46)      Branches: 0% (0 / 28)      Functions: 0% (0 / 5)      Lines: 28.57% (10 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541 1   1   1   1                               1   1             1         1                 1              
var stream = require('readable-stream')
var inherits = require('inherits')
 
var SIGNAL_FLUSH = new Buffer([0])
 
module.exports = WriteStream
 
function WriteStream (opts, write, flush) {
  if (!(this instanceof WriteStream)) return new WriteStream(opts, write, flush)
 
  if (typeof opts === 'function') {
    flush = write
    write = opts
    opts = {}
  }
 
  stream.Writable.call(this, opts)
 
  this.destroyed = false
  this._worker = write || null
  this._flush = flush || null
}
 
inherits(WriteStream, stream.Writable)
 
WriteStream.obj = function (opts, worker, flush) {
  if (typeof opts === 'function') return WriteStream.obj(null, opts, worker)
  if (!opts) opts = {}
  opts.objectMode = true
  return new WriteStream(opts, worker, flush)
}
 
WriteStream.prototype._write = function (data, enc, cb) {
  if (SIGNAL_FLUSH === data) this._flush(cb)
  else this._worker(data, enc, cb)
}
 
WriteStream.prototype.end = function (data, enc, cb) {
  if (!this._flush) return stream.Writable.prototype.end.apply(this, arguments)
  if (typeof data === 'function') return this.end(null, null, data)
  if (typeof enc === 'function') return this.end(data, null, enc)
  if (data) this.write(data)
  if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  return stream.Writable.prototype.end.call(this, cb)
}
 
WriteStream.prototype.destroy = function (err) {
  if (this.destroyed) return
  this.destroyed = true
  if (err) this.emit('error', err)
  this.emit('close')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/from2/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/from2/

Statements: 30.67% (23 / 75)      Branches: 11.9% (5 / 42)      Functions: 16.67% (2 / 12)      Lines: 34.33% (23 / 67)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/from2/
File Statements Branches Functions Lines
index.js 30.67% (23 / 75) 11.9% (5 / 42) 16.67% (2 / 12) 34.33% (23 / 67)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/from2/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/from2/index.js

Statements: 30.67% (23 / 75)      Branches: 11.9% (5 / 42)      Functions: 16.67% (2 / 12)      Lines: 34.33% (23 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 1051 1   1   1 1   1   1                           1                     1 1         1   1 1                   1                 1 1           1                     1     1                         1   1 1 1      
var Readable = require('readable-stream').Readable
var inherits = require('inherits')
 
module.exports = from2
 
from2.ctor = ctor
from2.obj = obj
 
var Proto = ctor()
 
function toFunction(list) {
  list = list.slice()
  return function (_, cb) {
    var err = null
    var item = list.length ? list.shift() : null
    if (item instanceof Error) {
      err = item
      item = null
    }
 
    cb(err, item)
  }
}
 
function from2(opts, read) {
  if (typeof opts !== 'object' || Array.isArray(opts)) {
    read = opts
    opts = {}
  }
 
  var rs = new Proto(opts)
  rs._from = Array.isArray(read) ? toFunction(read) : (read || noop)
  return rs
}
 
function ctor(opts, read) {
  Iif (typeof opts === 'function') {
    read = opts
    opts = {}
  }
 
  opts = defaults(opts)
 
  inherits(Class, Readable)
  function Class(override) {
    if (!(this instanceof Class)) return new Class(override)
    this._reading = false
    this._callback = check
    this.destroyed = false
    Readable.call(this, override || opts)
 
    var self = this
    var hwm = this._readableState.highWaterMark
 
    function check(err, data) {
      if (self.destroyed) return
      if (err) return self.destroy(err)
      if (data === null) return self.push(null)
      self._reading = false
      if (self.push(data)) self._read(hwm)
    }
  }
 
  Class.prototype._from = read || noop
  Class.prototype._read = function(size) {
    if (this._reading || this.destroyed) return
    this._reading = true
    this._from(size, this._callback)
  }
 
  Class.prototype.destroy = function(err) {
    if (this.destroyed) return
    this.destroyed = true
 
    var self = this
    process.nextTick(function() {
      if (err) self.emit('error', err)
      self.emit('close')
    })
  }
 
  return Class
}
 
function obj(opts, read) {
  if (typeof opts === 'function' || Array.isArray(opts)) {
    read = opts
    opts = {}
  }
 
  opts = defaults(opts)
  opts.objectMode = true
  opts.highWaterMark = 16
 
  return from2(opts, read)
}
 
function noop () {}
 
function defaults(opts) {
  opts = opts || {}
  return opts
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pump/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pump/

Statements: 19.35% (12 / 62)      Branches: 0% (0 / 40)      Functions: 0% (0 / 13)      Lines: 24% (12 / 50)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pump/
File Statements Branches Functions Lines
index.js 19.35% (12 / 62) 0% (0 / 40) 0% (0 / 13) 24% (12 / 50)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pump/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pump/index.js

Statements: 19.35% (12 / 62)      Branches: 0% (0 / 40)      Functions: 0% (0 / 13)      Lines: 24% (12 / 50)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 821 1 1   1   1       1         1       1                                                         1       1       1                                             1    
var once = require('once')
var eos = require('end-of-stream')
var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes
 
var noop = function () {}
 
var isFn = function (fn) {
  return typeof fn === 'function'
}
 
var isFS = function (stream) {
  if (!fs) return false // browser
  return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
}
 
var isRequest = function (stream) {
  return stream.setHeader && isFn(stream.abort)
}
 
var destroyer = function (stream, reading, writing, callback) {
  callback = once(callback)
 
  var closed = false
  stream.on('close', function () {
    closed = true
  })
 
  eos(stream, {readable: reading, writable: writing}, function (err) {
    if (err) return callback(err)
    closed = true
    callback()
  })
 
  var destroyed = false
  return function (err) {
    if (closed) return
    if (destroyed) return
    destroyed = true
 
    if (isFS(stream)) return stream.close() // use close for fs streams to avoid fd leaks
    if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
 
    if (isFn(stream.destroy)) return stream.destroy()
 
    callback(err || new Error('stream was destroyed'))
  }
}
 
var call = function (fn) {
  fn()
}
 
var pipe = function (from, to) {
  return from.pipe(to)
}
 
var pump = function () {
  var streams = Array.prototype.slice.call(arguments)
  var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop
 
  if (Array.isArray(streams[0])) streams = streams[0]
  if (streams.length < 2) throw new Error('pump requires two streams per minimum')
 
  var error
  var destroys = streams.map(function (stream, i) {
    var reading = i < streams.length - 1
    var writing = i > 0
    return destroyer(stream, reading, writing, function (err) {
      if (!error) error = err
      if (err) destroys.forEach(call)
      if (reading) return
      destroys.forEach(call)
      callback(error)
    })
  })
 
  return streams.reduce(pipe)
}
 
module.exports = pump
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pumpify/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pumpify/

Statements: 25.58% (11 / 43)      Branches: 0% (0 / 18)      Functions: 14.29% (1 / 7)      Lines: 29.73% (11 / 37)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pumpify/
File Statements Branches Functions Lines
index.js 25.58% (11 / 43) 0% (0 / 18) 14.29% (1 / 7) 29.73% (11 / 37)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pumpify/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/pumpify/index.js

Statements: 25.58% (11 / 43)      Branches: 0% (0 / 18)      Functions: 14.29% (1 / 7)      Lines: 29.73% (11 / 37)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571 1 1   1         1 2             2   2                                                             2     1 1    
var pump = require('pump')
var inherits = require('inherits')
var Duplexify = require('duplexify')
 
var toArray = function(args) {
  if (!args.length) return []
  return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args)
}
 
var define = function(opts) {
  var Pumpify = function() {
    var streams = toArray(arguments)
    if (!(this instanceof Pumpify)) return new Pumpify(streams)
    Duplexify.call(this, null, null, opts)
    if (streams.length) this.setPipeline(streams)
  }
 
  inherits(Pumpify, Duplexify)
 
  Pumpify.prototype.setPipeline = function() {
    var streams = toArray(arguments)
    var self = this
    var ended = false
    var w = streams[0]
    var r = streams[streams.length-1]
 
    r = r.readable ? r : null
    w = w.writable ? w : null
 
    var onclose = function() {
      streams[0].emit('error', new Error('stream was destroyed'))
    }
 
    this.on('close', onclose)
    this.on('prefinish', function() {
      if (!ended) self.cork()
    })
 
    pump(streams, function(err) {
      self.removeListener('close', onclose)
      if (err) return self.destroy(err)
      ended = true
      self.uncork()
    })
 
    if (this.destroyed) return onclose()
    this.setWritable(w)
    this.setReadable(r)
  }
 
  return Pumpify
}
 
module.exports = define({destroy:false})
module.exports.obj = define({destroy:false, objectMode:true, highWaterMark:16})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/

Statements: 18.6% (8 / 43)      Branches: 0% (0 / 20)      Functions: 0% (0 / 5)      Lines: 22.22% (8 / 36)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/
File Statements Branches Functions Lines
index.js 18.6% (8 / 43) 0% (0 / 20) 0% (0 / 5) 22.22% (8 / 36)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/index.js

Statements: 18.6% (8 / 43)      Branches: 0% (0 / 20)      Functions: 0% (0 / 5)      Lines: 22.22% (8 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561 1   1   1                       1           1       1                         1                              
var eos = require('end-of-stream')
var shift = require('stream-shift')
 
module.exports = each
 
function each (stream, fn, cb) {
  var want = true
  var error = null
  var ended = false
  var running = false
 
  stream.on('readable', onreadable)
  onreadable()
 
  if (cb) eos(stream, {readable: true, writable: false}, done)
  return stream
 
  function done (err) {
    if (!error) error = err
    ended = true
    if (!running) cb(error)
  }
 
  function onreadable () {
    if (want) read()
  }
 
  function afterRead (err) {
    running = false
 
    if (err) {
      error = err
      if (ended) return cb(error)
      stream.destroy(err)
      return
    }
    if (ended) return cb(error)
    read()
  }
 
  function read () {
    if (ended || running) return
    want = false
 
    var data = shift(stream)
    if (!data) {
      want = true
      return
    }
 
    running = true
    fn(data, afterRead)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/node_modules/stream-shift/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/node_modules/stream-shift/

Statements: 25% (3 / 12)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 27.27% (3 / 11)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/node_modules/stream-shift/
File Statements Branches Functions Lines
index.js 25% (3 / 12) 0% (0 / 8) 0% (0 / 2) 27.27% (3 / 11)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/node_modules/stream-shift/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/stream-each/node_modules/stream-shift/index.js

Statements: 25% (3 / 12)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 27.27% (3 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 221   1           1                          
module.exports = shift
 
function shift (stream) {
  var rs = stream._readableState
  if (!rs) return null
  return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
}
 
function getStateLength (state) {
  if (state.buffer.length) {
    // Since node 6.3.0 state.buffer is a BufferList not an array
    if (state.buffer.head) {
      return state.buffer.head.data.length
    }
 
    return state.buffer[0].length
  }
 
  return state.length
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/

Statements: 22% (11 / 50)      Branches: 0% (0 / 18)      Functions: 10% (1 / 10)      Lines: 22.45% (11 / 49)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/
File Statements Branches Functions Lines
through2.js 22% (11 / 50) 0% (0 / 18) 10% (1 / 10) 22.45% (11 / 49)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/through2.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/through2.js

Statements: 22% (11 / 50)      Branches: 0% (0 / 18)      Functions: 10% (1 / 10)      Lines: 22.45% (11 / 49)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 981       1         1   1                         1             1 3                                     1                           1 1                                       1                      
var Transform = require('readable-stream/transform')
  , inherits  = require('util').inherits
  , xtend     = require('xtend')
 
function DestroyableTransform(opts) {
  Transform.call(this, opts)
  this._destroyed = false
}
 
inherits(DestroyableTransform, Transform)
 
DestroyableTransform.prototype.destroy = function(err) {
  if (this._destroyed) return
  this._destroyed = true
  
  var self = this
  process.nextTick(function() {
    if (err)
      self.emit('error', err)
    self.emit('close')
  })
}
 
// a noop _transform function
function noop (chunk, enc, callback) {
  callback(null, chunk)
}
 
 
// create a new export function, used by both the main export and
// the .ctor export, contains common logic for dealing with arguments
function through2 (construct) {
  return function (options, transform, flush) {
    if (typeof options == 'function') {
      flush     = transform
      transform = options
      options   = {}
    }
 
    if (typeof transform != 'function')
      transform = noop
 
    if (typeof flush != 'function')
      flush = null
 
    return construct(options, transform, flush)
  }
}
 
 
// main export, just make me a transform stream!
module.exports = through2(function (options, transform, flush) {
  var t2 = new DestroyableTransform(options)
 
  t2._transform = transform
 
  if (flush)
    t2._flush = flush
 
  return t2
})
 
 
// make me a reusable prototype that I can `new`, or implicitly `new`
// with a constructor call
module.exports.ctor = through2(function (options, transform, flush) {
  function Through2 (override) {
    if (!(this instanceof Through2))
      return new Through2(override)
 
    this.options = xtend(options, override)
 
    DestroyableTransform.call(this, this.options)
  }
 
  inherits(Through2, DestroyableTransform)
 
  Through2.prototype._transform = transform
 
  if (flush)
    Through2.prototype._flush = flush
 
  return Through2
})
 
 
module.exports.obj = through2(function (options, transform, flush) {
  var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options))
 
  t2._transform = transform
 
  if (flush)
    t2._flush = flush
 
  return t2
})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/node_modules/xtend/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/node_modules/xtend/

Statements: 30% (3 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 30% (3 / 10)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/node_modules/xtend/
File Statements Branches Functions Lines
immutable.js 30% (3 / 10) 0% (0 / 2) 0% (0 / 1) 30% (3 / 10)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/node_modules/xtend/immutable.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mississippi/node_modules/through2/node_modules/xtend/immutable.js

Statements: 30% (3 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 30% (3 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 211   1   1                                
module.exports = extend
 
var hasOwnProperty = Object.prototype.hasOwnProperty;
 
function extend() {
    var target = {}
 
    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i]
 
        for (var key in source) {
            if (hasOwnProperty.call(source, key)) {
                target[key] = source[key]
            }
        }
    }
 
    return target
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mkdirp/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mkdirp/

Statements: 10.34% (6 / 58)      Branches: 0% (0 / 42)      Functions: 0% (0 / 6)      Lines: 11.32% (6 / 53)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/mkdirp/
File Statements Branches Functions Lines
index.js 10.34% (6 / 58) 0% (0 / 42) 0% (0 / 6) 11.32% (6 / 53)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mkdirp/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/mkdirp/index.js

Statements: 10.34% (6 / 58)      Branches: 0% (0 / 42)      Functions: 0% (0 / 6)      Lines: 11.32% (6 / 53)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 1001 1 1   1   1                                                                                               1                                                                                          
var path = require('path');
var fs = require('fs');
var _0777 = parseInt('0777', 8);
 
module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
 
function mkdirP (p, opts, f, made) {
    if (typeof opts === 'function') {
        f = opts;
        opts = {};
    }
    else if (!opts || typeof opts !== 'object') {
        opts = { mode: opts };
    }
    
    var mode = opts.mode;
    var xfs = opts.fs || fs;
    
    if (mode === undefined) {
        mode = _0777 & (~process.umask());
    }
    if (!made) made = null;
    
    var cb = f || function () {};
    p = path.resolve(p);
    
    xfs.mkdir(p, mode, function (er) {
        if (!er) {
            made = made || p;
            return cb(null, made);
        }
        switch (er.code) {
            case 'ENOENT':
                mkdirP(path.dirname(p), opts, function (er, made) {
                    if (er) cb(er, made);
                    else mkdirP(p, opts, cb, made);
                });
                break;
 
            // In the case of any other error, just see if there's a dir
            // there already.  If so, then hooray!  If not, then something
            // is borked.
            default:
                xfs.stat(p, function (er2, stat) {
                    // if the stat fails, then that's super weird.
                    // let the original error be the failure reason.
                    if (er2 || !stat.isDirectory()) cb(er, made)
                    else cb(null, made);
                });
                break;
        }
    });
}
 
mkdirP.sync = function sync (p, opts, made) {
    if (!opts || typeof opts !== 'object') {
        opts = { mode: opts };
    }
    
    var mode = opts.mode;
    var xfs = opts.fs || fs;
    
    if (mode === undefined) {
        mode = _0777 & (~process.umask());
    }
    if (!made) made = null;
 
    p = path.resolve(p);
 
    try {
        xfs.mkdirSync(p, mode);
        made = made || p;
    }
    catch (err0) {
        switch (err0.code) {
            case 'ENOENT' :
                made = sync(path.dirname(p), opts, made);
                sync(p, opts, made);
                break;
 
            // In the case of any other error, just see if there's a dir
            // there already.  If so, then hooray!  If not, then something
            // is borked.
            default:
                var stat;
                try {
                    stat = xfs.statSync(p);
                }
                catch (err1) {
                    throw err0;
                }
                if (!stat.isDirectory()) throw err0;
                break;
        }
    }
 
    return made;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/lib/

Statements: 6.37% (17 / 267)      Branches: 1.35% (3 / 223)      Functions: 0% (0 / 23)      Lines: 7.02% (17 / 242)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/nopt/lib/
File Statements Branches Functions Lines
nopt.js 6.37% (17 / 267) 1.35% (3 / 223) 0% (0 / 23) 7.02% (17 / 242)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/lib/nopt.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/lib/nopt.js

Statements: 6.37% (17 / 267)      Branches: 1.35% (3 / 223)      Functions: 0% (0 / 23)      Lines: 7.02% (17 / 242)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438    1       1           1 1   1                   1                                                     1                                                                                                                                                 1       1                                   1           1             1                   1           1         1                                                                                                             1                                                                                                                                                                                                                                                                                           1                                                                                                                      
// info about each config option.
 
var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG
  ? function () { console.error.apply(console, arguments) }
  : function () {}
 
var url = require("url")
  , path = require("path")
  , Stream = require("stream").Stream
  , abbrev = require("abbrev")
  , osenv = require("osenv")
 
module.exports = exports = nopt
exports.clean = clean
 
exports.typeDefs =
  { String  : { type: String,  validate: validateString  }
  , Boolean : { type: Boolean, validate: validateBoolean }
  , url     : { type: url,     validate: validateUrl     }
  , Number  : { type: Number,  validate: validateNumber  }
  , path    : { type: path,    validate: validatePath    }
  , Stream  : { type: Stream,  validate: validateStream  }
  , Date    : { type: Date,    validate: validateDate    }
  }
 
function nopt (types, shorthands, args, slice) {
  args = args || process.argv
  types = types || {}
  shorthands = shorthands || {}
  if (typeof slice !== "number") slice = 2
 
  debug(types, shorthands, args, slice)
 
  args = args.slice(slice)
  var data = {}
    , key
    , argv = {
        remain: [],
        cooked: args,
        original: args.slice(0)
      }
 
  parse(args, data, argv.remain, types, shorthands)
  // now data is full
  clean(data, types, exports.typeDefs)
  data.argv = argv
  Object.defineProperty(data.argv, 'toString', { value: function () {
    return this.original.map(JSON.stringify).join(" ")
  }, enumerable: false })
  return data
}
 
function clean (data, types, typeDefs) {
  typeDefs = typeDefs || exports.typeDefs
  var remove = {}
    , typeDefault = [false, true, null, String, Array]
 
  Object.keys(data).forEach(function (k) {
    if (k === "argv") return
    var val = data[k]
      , isArray = Array.isArray(val)
      , type = types[k]
    if (!isArray) val = [val]
    if (!type) type = typeDefault
    if (type === Array) type = typeDefault.concat(Array)
    if (!Array.isArray(type)) type = [type]
 
    debug("val=%j", val)
    debug("types=", type)
    val = val.map(function (val) {
      // if it's an unknown value, then parse false/true/null/numbers/dates
      if (typeof val === "string") {
        debug("string %j", val)
        val = val.trim()
        if ((val === "null" && ~type.indexOf(null))
            || (val === "true" &&
               (~type.indexOf(true) || ~type.indexOf(Boolean)))
            || (val === "false" &&
               (~type.indexOf(false) || ~type.indexOf(Boolean)))) {
          val = JSON.parse(val)
          debug("jsonable %j", val)
        } else if (~type.indexOf(Number) && !isNaN(val)) {
          debug("convert to number", val)
          val = +val
        } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) {
          debug("convert to date", val)
          val = new Date(val)
        }
      }
 
      if (!types.hasOwnProperty(k)) {
        return val
      }
 
      // allow `--no-blah` to set 'blah' to null if null is allowed
      if (val === false && ~type.indexOf(null) &&
          !(~type.indexOf(false) || ~type.indexOf(Boolean))) {
        val = null
      }
 
      var d = {}
      d[k] = val
      debug("prevalidated val", d, val, types[k])
      if (!validate(d, k, val, types[k], typeDefs)) {
        if (exports.invalidHandler) {
          exports.invalidHandler(k, val, types[k], data)
        } else if (exports.invalidHandler !== false) {
          debug("invalid: "+k+"="+val, types[k])
        }
        return remove
      }
      debug("validated val", d, val, types[k])
      return d[k]
    }).filter(function (val) { return val !== remove })
 
    if (!val.length) delete data[k]
    else if (isArray) {
      debug(isArray, data[k], val)
      data[k] = val
    } else data[k] = val[0]
 
    debug("k=%s val=%j", k, val, data[k])
  })
}
 
function validateString (data, k, val) {
  data[k] = String(val)
}
 
function validatePath (data, k, val) {
  if (val === true) return false
  if (val === null) return true
 
  val = String(val)
 
  var isWin       = process.platform === 'win32'
    , homePattern = isWin ? /^~(\/|\\)/ : /^~\//
    , home        = osenv.home()
 
  if (home && val.match(homePattern)) {
    data[k] = path.resolve(home, val.substr(2))
  } else {
    data[k] = path.resolve(val)
  }
  return true
}
 
function validateNumber (data, k, val) {
  debug("validate Number %j %j %j", k, val, isNaN(val))
  if (isNaN(val)) return false
  data[k] = +val
}
 
function validateDate (data, k, val) {
  var s = Date.parse(val)
  debug("validate Date %j %j %j", k, val, s)
  if (isNaN(s)) return false
  data[k] = new Date(val)
}
 
function validateBoolean (data, k, val) {
  if (val instanceof Boolean) val = val.valueOf()
  else if (typeof val === "string") {
    if (!isNaN(val)) val = !!(+val)
    else if (val === "null" || val === "false") val = false
    else val = true
  } else val = !!val
  data[k] = val
}
 
function validateUrl (data, k, val) {
  val = url.parse(String(val))
  if (!val.host) return false
  data[k] = val.href
}
 
function validateStream (data, k, val) {
  if (!(val instanceof Stream)) return false
  data[k] = val
}
 
function validate (data, k, val, type, typeDefs) {
  // arrays are lists of types.
  if (Array.isArray(type)) {
    for (var i = 0, l = type.length; i < l; i ++) {
      if (type[i] === Array) continue
      if (validate(data, k, val, type[i], typeDefs)) return true
    }
    delete data[k]
    return false
  }
 
  // an array of anything?
  if (type === Array) return true
 
  // NaN is poisonous.  Means that something is not allowed.
  if (type !== type) {
    debug("Poison NaN", k, val, type)
    delete data[k]
    return false
  }
 
  // explicit list of values
  if (val === type) {
    debug("Explicitly allowed %j", val)
    // if (isArray) (data[k] = data[k] || []).push(val)
    // else data[k] = val
    data[k] = val
    return true
  }
 
  // now go through the list of typeDefs, validate against each one.
  var ok = false
    , types = Object.keys(typeDefs)
  for (var i = 0, l = types.length; i < l; i ++) {
    debug("test type %j %j %j", k, val, types[i])
    var t = typeDefs[types[i]]
    if (t &&
      ((type && type.name && t.type && t.type.name) ? (type.name === t.type.name) : (type === t.type))) {
      var d = {}
      ok = false !== t.validate(d, k, val)
      val = d[k]
      if (ok) {
        // if (isArray) (data[k] = data[k] || []).push(val)
        // else data[k] = val
        data[k] = val
        break
      }
    }
  }
  debug("OK? %j (%j %j %j)", ok, k, val, types[i])
 
  if (!ok) delete data[k]
  return ok
}
 
function parse (args, data, remain, types, shorthands) {
  debug("parse", args, data, remain)
 
  var key = null
    , abbrevs = abbrev(Object.keys(types))
    , shortAbbr = abbrev(Object.keys(shorthands))
 
  for (var i = 0; i < args.length; i ++) {
    var arg = args[i]
    debug("arg", arg)
 
    if (arg.match(/^-{2,}$/)) {
      // done with keys.
      // the rest are args.
      remain.push.apply(remain, args.slice(i + 1))
      args[i] = "--"
      break
    }
    var hadEq = false
    if (arg.charAt(0) === "-" && arg.length > 1) {
      var at = arg.indexOf('=')
      if (at > -1) {
        hadEq = true
        var v = arg.substr(at + 1)
        arg = arg.substr(0, at)
        args.splice(i, 1, arg, v)
      }
 
      // see if it's a shorthand
      // if so, splice and back up to re-parse it.
      var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs)
      debug("arg=%j shRes=%j", arg, shRes)
      if (shRes) {
        debug(arg, shRes)
        args.splice.apply(args, [i, 1].concat(shRes))
        if (arg !== shRes[0]) {
          i --
          continue
        }
      }
      arg = arg.replace(/^-+/, "")
      var no = null
      while (arg.toLowerCase().indexOf("no-") === 0) {
        no = !no
        arg = arg.substr(3)
      }
 
      if (abbrevs[arg]) arg = abbrevs[arg]
 
      var argType = types[arg]
      var isTypeArray = Array.isArray(argType)
      if (isTypeArray && argType.length === 1) {
        isTypeArray = false
        argType = argType[0]
      }
 
      var isArray = argType === Array ||
        isTypeArray && argType.indexOf(Array) !== -1
 
      // allow unknown things to be arrays if specified multiple times.
      if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) {
        if (!Array.isArray(data[arg]))
          data[arg] = [data[arg]]
        isArray = true
      }
 
      var val
        , la = args[i + 1]
 
      var isBool = typeof no === 'boolean' ||
        argType === Boolean ||
        isTypeArray && argType.indexOf(Boolean) !== -1 ||
        (typeof argType === 'undefined' && !hadEq) ||
        (la === "false" &&
         (argType === null ||
          isTypeArray && ~argType.indexOf(null)))
 
      if (isBool) {
        // just set and move along
        val = !no
        // however, also support --bool true or --bool false
        if (la === "true" || la === "false") {
          val = JSON.parse(la)
          la = null
          if (no) val = !val
          i ++
        }
 
        // also support "foo":[Boolean, "bar"] and "--foo bar"
        if (isTypeArray && la) {
          if (~argType.indexOf(la)) {
            // an explicit type
            val = la
            i ++
          } else if ( la === "null" && ~argType.indexOf(null) ) {
            // null allowed
            val = null
            i ++
          } else if ( !la.match(/^-{2,}[^-]/) &&
                      !isNaN(la) &&
                      ~argType.indexOf(Number) ) {
            // number
            val = +la
            i ++
          } else if ( !la.match(/^-[^-]/) && ~argType.indexOf(String) ) {
            // string
            val = la
            i ++
          }
        }
 
        if (isArray) (data[arg] = data[arg] || []).push(val)
        else data[arg] = val
 
        continue
      }
 
      if (argType === String) {
        if (la === undefined) {
          la = ""
        } else if (la.match(/^-{1,2}[^-]+/)) {
          la = ""
          i --
        }
      }
 
      if (la && la.match(/^-{2,}$/)) {
        la = undefined
        i --
      }
 
      val = la === undefined ? true : la
      if (isArray) (data[arg] = data[arg] || []).push(val)
      else data[arg] = val
 
      i ++
      continue
    }
    remain.push(arg)
  }
}
 
function resolveShort (arg, shorthands, shortAbbr, abbrevs) {
  // handle single-char shorthands glommed together, like
  // npm ls -glp, but only if there is one dash, and only if
  // all of the chars are single-char shorthands, and it's
  // not a match to some other abbrev.
  arg = arg.replace(/^-+/, '')
 
  // if it's an exact known option, then don't go any further
  if (abbrevs[arg] === arg)
    return null
 
  // if it's an exact known shortopt, same deal
  if (shorthands[arg]) {
    // make it an array, if it's a list of words
    if (shorthands[arg] && !Array.isArray(shorthands[arg]))
      shorthands[arg] = shorthands[arg].split(/\s+/)
 
    return shorthands[arg]
  }
 
  // first check to see if this arg is a set of single-char shorthands
  var singles = shorthands.___singles
  if (!singles) {
    singles = Object.keys(shorthands).filter(function (s) {
      return s.length === 1
    }).reduce(function (l,r) {
      l[r] = true
      return l
    }, {})
    shorthands.___singles = singles
    debug('shorthand singles', singles)
  }
 
  var chrs = arg.split("").filter(function (c) {
    return singles[c]
  })
 
  if (chrs.join("") === arg) return chrs.map(function (c) {
    return shorthands[c]
  }).reduce(function (l, r) {
    return l.concat(r)
  }, [])
 
 
  // if it's an arg abbrev, and not a literal shorthand, then prefer the arg
  if (abbrevs[arg] && !shorthands[arg])
    return null
 
  // if it's an abbr for a shorthand, then use that
  if (shortAbbr[arg])
    arg = shortAbbr[arg]
 
  // make it an array, if it's a list of words
  if (shorthands[arg] && !Array.isArray(shorthands[arg]))
    shorthands[arg] = shorthands[arg].split(/\s+/)
 
  return shorthands[arg]
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/

Statements: 41.46% (17 / 41)      Branches: 0% (0 / 36)      Functions: 8.33% (1 / 12)      Lines: 44.74% (17 / 38)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/
File Statements Branches Functions Lines
osenv.js 41.46% (17 / 41) 0% (0 / 36) 8.33% (1 / 12) 44.74% (17 / 38)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/osenv.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/osenv.js

Statements: 41.46% (17 / 41)      Branches: 0% (0 / 36)      Functions: 8.33% (1 / 12)      Lines: 44.74% (17 / 38)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 741 1 1 1 1           1 8 8 8                                       1             1       1       1       1       1           1           1          
var isWindows = process.platform === 'win32'
var path = require('path')
var exec = require('child_process').exec
var osTmpdir = require('os-tmpdir')
var osHomedir = require('os-homedir')
 
// looking up envs is a bit costly.
// Also, sometimes we want to have a fallback
// Pass in a callback to wait for the fallback on failures
// After the first lookup, always returns the same thing.
function memo (key, lookup, fallback) {
  var fell = false
  var falling = false
  exports[key] = function (cb) {
    var val = lookup()
    if (!val && !fell && !falling && fallback) {
      fell = true
      falling = true
      exec(fallback, function (er, output, stderr) {
        falling = false
        if (er) return // oh well, we tried
        val = output.trim()
      })
    }
    exports[key] = function (cb) {
      if (cb) process.nextTick(cb.bind(null, null, val))
      return val
    }
    if (cb && !falling) process.nextTick(cb.bind(null, null, val))
    return val
  }
}
 
memo('user', function () {
  return ( isWindows
         ? process.env.USERDOMAIN + '\\' + process.env.USERNAME
         : process.env.USER
         )
}, 'whoami')
 
memo('prompt', function () {
  return isWindows ? process.env.PROMPT : process.env.PS1
})
 
memo('hostname', function () {
  return isWindows ? process.env.COMPUTERNAME : process.env.HOSTNAME
}, 'hostname')
 
memo('tmpdir', function () {
  return osTmpdir()
})
 
memo('home', function () {
  return osHomedir()
})
 
memo('path', function () {
  return (process.env.PATH ||
          process.env.Path ||
          process.env.path).split(isWindows ? ';' : ':')
})
 
memo('editor', function () {
  return process.env.EDITOR ||
         process.env.VISUAL ||
         (isWindows ? 'notepad.exe' : 'vi')
})
 
memo('shell', function () {
  return isWindows ? process.env.ComSpec || 'cmd'
         : process.env.SHELL || 'bash'
})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/

Statements: 23.08% (3 / 13)      Branches: 3.57% (1 / 28)      Functions: 0% (0 / 1)      Lines: 23.08% (3 / 13)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/
File Statements Branches Functions Lines
index.js 23.08% (3 / 13) 3.57% (1 / 28) 0% (0 / 1) 23.08% (3 / 13)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/index.js

Statements: 23.08% (3 / 13)      Branches: 3.57% (1 / 28)      Functions: 0% (0 / 1)      Lines: 23.08% (3 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  1   1                                       1    
'use strict';
var os = require('os');
 
function homedir() {
	var env = process.env;
	var home = env.HOME;
	var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
 
	if (process.platform === 'win32') {
		return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null;
	}
 
	if (process.platform === 'darwin') {
		return home || (user ? '/Users/' + user : null);
	}
 
	if (process.platform === 'linux') {
		return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null));
	}
 
	return home || null;
}
 
module.exports = typeof os.homedir === 'function' ? os.homedir : homedir;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/

Statements: 30% (3 / 10)      Branches: 6.67% (1 / 15)      Functions: 0% (0 / 1)      Lines: 30% (3 / 10)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/
File Statements Branches Functions Lines
index.js 30% (3 / 10) 6.67% (1 / 15) 0% (0 / 1) 30% (3 / 10)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/index.js

Statements: 30% (3 / 10)      Branches: 6.67% (1 / 15)      Functions: 0% (0 / 1)      Lines: 30% (3 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1 1     1                                          
'use strict';
var isWindows = process.platform === 'win32';
var trailingSlashRe = isWindows ? /[^:]\\$/ : /.\/$/;
 
// https://github.com/nodejs/node/blob/3e7a14381497a3b73dda68d05b5130563cdab420/lib/os.js#L25-L43
module.exports = function () {
	var path;
 
	if (isWindows) {
		path = process.env.TEMP ||
			process.env.TMP ||
			(process.env.SystemRoot || process.env.windir) + '\\temp';
	} else {
		path = process.env.TMPDIR ||
			process.env.TMP ||
			process.env.TEMP ||
			'/tmp';
	}
 
	if (trailingSlashRe.test(path)) {
		path = path.slice(0, -1);
	}
 
	return path;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-git-url/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-git-url/

Statements: 11.11% (2 / 18)      Branches: 0% (0 / 13)      Functions: 0% (0 / 1)      Lines: 11.11% (2 / 18)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/normalize-git-url/
File Statements Branches Functions Lines
normalize-git-url.js 11.11% (2 / 18) 0% (0 / 13) 0% (0 / 1) 11.11% (2 / 18)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-git-url/normalize-git-url.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-git-url/normalize-git-url.js

Statements: 11.11% (2 / 18)      Branches: 0% (0 / 13)      Functions: 0% (0 / 1)      Lines: 11.11% (2 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 421   1                                                                              
var url = require('url')
 
module.exports = function normalize (u) {
  var parsed = url.parse(u)
  // If parsing actually alters the URL, it is almost certainly an
  // scp-style URL, or an invalid one.
  var altered = u !== url.format(parsed)
 
  // git is so tricky!
  // if the path is like ssh://foo:22/some/path then it works, but
  // it needs the ssh://
  // If the path is like ssh://foo:some/path then it works, but
  // only if you remove the ssh://
  if (parsed.protocol) {
    parsed.protocol = parsed.protocol.replace(/^git\+/, '')
  }
 
  // figure out what we should check out.
  var checkout = parsed.hash && parsed.hash.substr(1) || 'master'
  parsed.hash = ''
 
  var returnedUrl
  if (altered) {
    if (u.match(/^git\+https?/) && parsed.pathname.match(/\/?:[^0-9]/)) {
      returnedUrl = u.replace(/^git\+(.*:[^:]+):(.*)/, '$1/$2')
    } else if (u.match(/^git\+file/)) {
      returnedUrl = u.replace(/^git\+/, '')
    } else {
      returnedUrl = u.replace(/^(?:git\+)?ssh:\/\//, '')
    }
    returnedUrl = returnedUrl.replace(/#[^#]*$/, '')
  } else {
    returnedUrl = url.format(parsed)
  }
 
  return {
    url: returnedUrl,
    branch: checkout
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/

Statements: 11.31% (37 / 327)      Branches: 0% (0 / 268)      Functions: 3.92% (2 / 51)      Lines: 12.54% (37 / 295)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/
File Statements Branches Functions Lines
extract_description.js 18.18% (2 / 11) 0% (0 / 8) 0% (0 / 1) 22.22% (2 / 9)
fixer.js 6.88% (19 / 276) 0% (0 / 241) 0% (0 / 42) 7.6% (19 / 250)
make_warning.js 26.67% (4 / 15) 0% (0 / 6) 0% (0 / 2) 26.67% (4 / 15)
normalize.js 48% (12 / 25) 0% (0 / 13) 33.33% (2 / 6) 57.14% (12 / 21)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/extract_description.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/extract_description.js

Statements: 18.18% (2 / 11)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 22.22% (2 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161     1                        
module.exports = extractDescription
 
// Extracts description from contents of a readme file in markdown format
function extractDescription (d) {
  if (!d) return;
  if (d === "ERROR: No README data found!") return;
  // the first block of text before the first heading
  // that isn't the first line heading
  d = d.trim().split('\n')
  for (var s = 0; d[s] && d[s].trim().match(/^(#|$)/); s ++);
  var l = d.length
  for (var e = s + 1; e < l && d[e].trim(); e ++);
  return d.slice(s, e).join(' ').trim()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/fixer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/fixer.js

Statements: 6.88% (19 / 276)      Branches: 0% (0 / 241)      Functions: 0% (0 / 42)      Lines: 7.6% (19 / 250)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 4201 1 1 1 1 1 1 1   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                     1         1                   1                 1                   1                       1                   1                                         1             1                      
var semver = require("semver")
var validateLicense = require('validate-npm-package-license');
var hostedGitInfo = require("hosted-git-info")
var isBuiltinModule = require("is-builtin-module")
var depTypes = ["dependencies","devDependencies","optionalDependencies"]
var extractDescription = require("./extract_description")
var url = require("url")
var typos = require("./typos")
 
var fixer = module.exports = {
  // default warning function
  warn: function() {},
 
  fixRepositoryField: function(data) {
    if (data.repositories) {
      this.warn("repositories");
      data.repository = data.repositories[0]
    }
    if (!data.repository) return this.warn("missingRepository")
    if (typeof data.repository === "string") {
      data.repository = {
        type: "git",
        url: data.repository
      }
    }
    var r = data.repository.url || ""
    if (r) {
      var hosted = hostedGitInfo.fromUrl(r)
      if (hosted) {
        r = data.repository.url
          = hosted.getDefaultRepresentation() == "shortcut" ? hosted.https() : hosted.toString()
      }
    }
 
    if (r.match(/github.com\/[^\/]+\/[^\/]+\.git\.git$/)) {
      this.warn("brokenGitUrl", r)
    }
  }
 
, fixTypos: function(data) {
    Object.keys(typos.topLevel).forEach(function (d) {
      if (data.hasOwnProperty(d)) {
        this.warn("typo", d, typos.topLevel[d])
      }
    }, this)
  }
 
, fixScriptsField: function(data) {
    if (!data.scripts) return
    if (typeof data.scripts !== "object") {
      this.warn("nonObjectScripts")
      delete data.scripts
      return
    }
    Object.keys(data.scripts).forEach(function (k) {
      if (typeof data.scripts[k] !== "string") {
        this.warn("nonStringScript")
        delete data.scripts[k]
      } else if (typos.script[k] && !data.scripts[typos.script[k]]) {
        this.warn("typo", k, typos.script[k], "scripts")
      }
    }, this)
  }
 
, fixFilesField: function(data) {
    var files = data.files
    if (files && !Array.isArray(files)) {
      this.warn("nonArrayFiles")
      delete data.files
    } else if (data.files) {
      data.files = data.files.filter(function(file) {
        if (!file || typeof file !== "string") {
          this.warn("invalidFilename", file)
          return false
        } else {
          return true
        }
      }, this)
    }
  }
 
, fixBinField: function(data) {
    if (!data.bin) return;
    if (typeof data.bin === "string") {
      var b = {}
      var match
      if (match = data.name.match(/^@[^/]+[/](.*)$/)) {
        b[match[1]] = data.bin
      } else {
        b[data.name] = data.bin
      }
      data.bin = b
    }
  }
 
, fixManField: function(data) {
    if (!data.man) return;
    if (typeof data.man === "string") {
      data.man = [ data.man ]
    }
  }
, fixBundleDependenciesField: function(data) {
    var bdd = "bundledDependencies"
    var bd = "bundleDependencies"
    if (data[bdd] && !data[bd]) {
      data[bd] = data[bdd]
      delete data[bdd]
    }
    if (data[bd] && !Array.isArray(data[bd])) {
      this.warn("nonArrayBundleDependencies")
      delete data[bd]
    } else if (data[bd]) {
      data[bd] = data[bd].filter(function(bd) {
        if (!bd || typeof bd !== 'string') {
          this.warn("nonStringBundleDependency", bd)
          return false
        } else {
          if (!data.dependencies) {
            data.dependencies = {}
          }
          if (!data.dependencies.hasOwnProperty(bd)) {
            this.warn("nonDependencyBundleDependency", bd)
            data.dependencies[bd] = "*"
          }
          return true
        }
      }, this)
    }
  }
 
, fixDependencies: function(data, strict) {
    var loose = !strict
    objectifyDeps(data, this.warn)
    addOptionalDepsToDeps(data, this.warn)
    this.fixBundleDependenciesField(data)
 
    ;['dependencies','devDependencies'].forEach(function(deps) {
      if (!(deps in data)) return
      if (!data[deps] || typeof data[deps] !== "object") {
        this.warn("nonObjectDependencies", deps)
        delete data[deps]
        return
      }
      Object.keys(data[deps]).forEach(function (d) {
        var r = data[deps][d]
        if (typeof r !== 'string') {
          this.warn("nonStringDependency", d, JSON.stringify(r))
          delete data[deps][d]
        }
        var hosted = hostedGitInfo.fromUrl(data[deps][d])
        if (hosted) data[deps][d] = hosted.toString()
      }, this)
    }, this)
  }
 
, fixModulesField: function (data) {
    if (data.modules) {
      this.warn("deprecatedModules")
      delete data.modules
    }
  }
 
, fixKeywordsField: function (data) {
    if (typeof data.keywords === "string") {
      data.keywords = data.keywords.split(/,\s+/)
    }
    if (data.keywords && !Array.isArray(data.keywords)) {
      delete data.keywords
      this.warn("nonArrayKeywords")
    } else if (data.keywords) {
      data.keywords = data.keywords.filter(function(kw) {
        if (typeof kw !== "string" || !kw) {
          this.warn("nonStringKeyword");
          return false
        } else {
          return true
        }
      }, this)
    }
  }
 
, fixVersionField: function(data, strict) {
    // allow "loose" semver 1.0 versions in non-strict mode
    // enforce strict semver 2.0 compliance in strict mode
    var loose = !strict
    if (!data.version) {
      data.version = ""
      return true
    }
    if (!semver.valid(data.version, loose)) {
      throw new Error('Invalid version: "'+ data.version + '"')
    }
    data.version = semver.clean(data.version, loose)
    return true
  }
 
, fixPeople: function(data) {
    modifyPeople(data, unParsePerson)
    modifyPeople(data, parsePerson)
  }
 
, fixNameField: function(data, options) {
    if (typeof options === "boolean") options = {strict: options}
    else if (typeof options === "undefined") options = {}
    var strict = options.strict
    if (!data.name && !strict) {
      data.name = ""
      return
    }
    if (typeof data.name !== "string") {
      throw new Error("name field must be a string.")
    }
    if (!strict)
      data.name = data.name.trim()
    ensureValidName(data.name, strict, options.allowLegacyCase)
    if (isBuiltinModule(data.name))
      this.warn("conflictingName", data.name)
  }
 
 
, fixDescriptionField: function (data) {
    if (data.description && typeof data.description !== 'string') {
      this.warn("nonStringDescription")
      delete data.description
    }
    if (data.readme && !data.description)
      data.description = extractDescription(data.readme)
      if(data.description === undefined) delete data.description;
    if (!data.description) this.warn("missingDescription")
  }
 
, fixReadmeField: function (data) {
    if (!data.readme) {
      this.warn("missingReadme")
      data.readme = "ERROR: No README data found!"
    }
  }
 
, fixBugsField: function(data) {
    if (!data.bugs && data.repository && data.repository.url) {
      var hosted = hostedGitInfo.fromUrl(data.repository.url)
      if(hosted && hosted.bugs()) {
        data.bugs = {url: hosted.bugs()}
      }
    }
    else if(data.bugs) {
      var emailRe = /^.+@.*\..+$/
      if(typeof data.bugs == "string") {
        if(emailRe.test(data.bugs))
          data.bugs = {email:data.bugs}
        else if(url.parse(data.bugs).protocol)
          data.bugs = {url: data.bugs}
        else
          this.warn("nonEmailUrlBugsString")
      }
      else {
        bugsTypos(data.bugs, this.warn)
        var oldBugs = data.bugs
        data.bugs = {}
        if(oldBugs.url) {
          if(typeof(oldBugs.url) == "string" && url.parse(oldBugs.url).protocol)
            data.bugs.url = oldBugs.url
          else
            this.warn("nonUrlBugsUrlField")
        }
        if(oldBugs.email) {
          if(typeof(oldBugs.email) == "string" && emailRe.test(oldBugs.email))
            data.bugs.email = oldBugs.email
          else
            this.warn("nonEmailBugsEmailField")
        }
      }
      if(!data.bugs.email && !data.bugs.url) {
        delete data.bugs
        this.warn("emptyNormalizedBugs")
      }
    }
  }
 
, fixHomepageField: function(data) {
    if (!data.homepage && data.repository && data.repository.url) {
      var hosted = hostedGitInfo.fromUrl(data.repository.url)
      if (hosted && hosted.docs()) data.homepage = hosted.docs()
    }
    if (!data.homepage) return
 
    if(typeof data.homepage !== "string") {
      this.warn("nonUrlHomepage")
      return delete data.homepage
    }
    if(!url.parse(data.homepage).protocol) {
      this.warn("missingProtocolHomepage")
      data.homepage = "http://" + data.homepage
    }
  }
 
, fixLicenseField: function(data) {
    if (!data.license) {
      return this.warn("missingLicense")
    } else{
      if (
        typeof(data.license) !== 'string' ||
        data.license.length < 1
      ) {
        this.warn("invalidLicense")
      } else {
        if (!validateLicense(data.license).validForNewPackages)
          this.warn("invalidLicense")
      }
    }
  }
}
 
function isValidScopedPackageName(spec) {
  if (spec.charAt(0) !== '@') return false
 
  var rest = spec.slice(1).split('/')
  if (rest.length !== 2) return false
 
  return rest[0] && rest[1] &&
    rest[0] === encodeURIComponent(rest[0]) &&
    rest[1] === encodeURIComponent(rest[1])
}
 
function isCorrectlyEncodedName(spec) {
  return !spec.match(/[\/@\s\+%:]/) &&
    spec === encodeURIComponent(spec)
}
 
function ensureValidName (name, strict, allowLegacyCase) {
  if (name.charAt(0) === "." ||
      !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) ||
      (strict && (!allowLegacyCase) && name !== name.toLowerCase()) ||
      name.toLowerCase() === "node_modules" ||
      name.toLowerCase() === "favicon.ico") {
        throw new Error("Invalid name: " + JSON.stringify(name))
  }
}
 
function modifyPeople (data, fn) {
  if (data.author) data.author = fn(data.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (!Array.isArray(data[set])) return;
    data[set] = data[set].map(fn)
  })
  return data
}
 
function unParsePerson (person) {
  if (typeof person === "string") return person
  var name = person.name || ""
  var u = person.url || person.web
  var url = u ? (" ("+u+")") : ""
  var e = person.email || person.mail
  var email = e ? (" <"+e+">") : ""
  return name+email+url
}
 
function parsePerson (person) {
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
  var url = person.match(/\(([^\)]+)\)/)
  var email = person.match(/<([^>]+)>/)
  var obj = {}
  if (name && name[0].trim()) obj.name = name[0].trim()
  if (email) obj.email = email[1];
  if (url) obj.url = url[1];
  return obj
}
 
function addOptionalDepsToDeps (data, warn) {
  var o = data.optionalDependencies
  if (!o) return;
  var d = data.dependencies || {}
  Object.keys(o).forEach(function (k) {
    d[k] = o[k]
  })
  data.dependencies = d
}
 
function depObjectify (deps, type, warn) {
  if (!deps) return {}
  if (typeof deps === "string") {
    deps = deps.trim().split(/[\n\r\s\t ,]+/)
  }
  if (!Array.isArray(deps)) return deps
  warn("deprecatedArrayDependencies", type)
  var o = {}
  deps.filter(function (d) {
    return typeof d === "string"
  }).forEach(function(d) {
    d = d.trim().split(/(:?[@\s><=])/)
    var dn = d.shift()
    var dv = d.join("")
    dv = dv.trim()
    dv = dv.replace(/^@/, "")
    o[dn] = dv
  })
  return o
}
 
function objectifyDeps (data, warn) {
  depTypes.forEach(function (type) {
    if (!data[type]) return;
    data[type] = depObjectify(data[type], type, warn)
  })
}
 
function bugsTypos(bugs, warn) {
  if (!bugs) return
  Object.keys(bugs).forEach(function (k) {
    if (typos.bugs[k]) {
      warn("typo", k, typos.bugs[k], "bugs")
      bugs[typos.bugs[k]] = bugs[k]
      delete bugs[k]
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/make_warning.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/make_warning.js

Statements: 26.67% (4 / 15)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 26.67% (4 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 251 1   1                         1                
var util = require("util")
var messages = require("./warning_messages.json")
 
module.exports = function() {
  var args = Array.prototype.slice.call(arguments, 0)
  var warningName = args.shift()
  if (warningName == "typo") {
    return makeTypoWarning.apply(null,args)
  }
  else {
    var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'"
    args.unshift(msgTemplate)
    return util.format.apply(null, args)
  }
}
 
function makeTypoWarning (providedName, probableName, field) {
  if (field) {
    providedName = field + "['" + providedName + "']"
    probableName = field + "['" + probableName + "']"
  }
  return util.format(messages.typo, providedName, probableName)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/normalize.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/lib/normalize.js

Statements: 48% (12 / 25)      Branches: 0% (0 / 13)      Functions: 33.33% (2 / 6)      Lines: 57.14% (12 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411   1 1   1   1   1   1 14         1   1                                 1 14      
module.exports = normalize
 
var fixer = require("./fixer")
normalize.fixer = fixer
 
var makeWarning = require("./make_warning")
 
var fieldsToFix = ['name','version','description','repository','modules','scripts'
                  ,'files','bin','man','bugs','keywords','readme','homepage','license']
var otherThingsToFix = ['dependencies','people', 'typos']
 
var thingsToFix = fieldsToFix.map(function(fieldName) {
  return ucFirst(fieldName) + "Field"
})
// two ways to do this in CoffeeScript on only one line, sub-70 chars:
// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field"
// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix)
thingsToFix = thingsToFix.concat(otherThingsToFix)
 
function normalize (data, warn, strict) {
  if(warn === true) warn = null, strict = true
  if(!strict) strict = false
  if(!warn || data.private) warn = function(msg) { /* noop */ }
 
  if (data.scripts &&
      data.scripts.install === "node-gyp rebuild" &&
      !data.scripts.preinstall) {
    data.gypfile = true
  }
  fixer.warn = function() { warn(makeWarning.apply(null, arguments)) }
  thingsToFix.forEach(function(thingName) {
    fixer["fix" + ucFirst(thingName)](data, strict)
  })
  data._id = data.name + "@" + data.version
}
 
function ucFirst (string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/

Statements: 40% (2 / 5)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 40% (2 / 5)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/
File Statements Branches Functions Lines
index.js 40% (2 / 5) 0% (0 / 2) 0% (0 / 1) 40% (2 / 5)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/index.js

Statements: 40% (2 / 5)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 40% (2 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12  1   1                
'use strict';
var builtinModules = require('builtin-modules');
 
module.exports = function (str) {
	if (typeof str !== 'string') {
		throw new TypeError('Expected a string');
	}
 
	return builtinModules.indexOf(str) !== -1;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/node_modules/builtin-modules/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/node_modules/builtin-modules/

Statements: 100% (3 / 3)      Branches: 100% (2 / 2)      Functions: 100% (1 / 1)      Lines: 100% (3 / 3)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/node_modules/builtin-modules/
File Statements Branches Functions Lines
index.js 100% (3 / 3) 100% (2 / 2) 100% (1 / 1) 100% (3 / 3)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/node_modules/builtin-modules/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/normalize-package-data/node_modules/is-builtin-module/node_modules/builtin-modules/index.js

Statements: 100% (3 / 3)      Branches: 100% (2 / 2)      Functions: 100% (1 / 1)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12    1         1 83      
'use strict';
 
var blacklist = [
	'freelist',
	'sys'
];
 
module.exports = Object.keys(process.binding('natives')).filter(function (el) {
	return !/^_|^internal|\//.test(el) && blacklist.indexOf(el) === -1;
}).sort();
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-cache-filename/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-cache-filename/

Statements: 26.67% (4 / 15)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 26.67% (4 / 15)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npm-cache-filename/
File Statements Branches Functions Lines
index.js 26.67% (4 / 15) 0% (0 / 6) 0% (0 / 2) 26.67% (4 / 15)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-cache-filename/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-cache-filename/index.js

Statements: 26.67% (4 / 15)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 26.67% (4 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 261 1   1   1                                        
var url = require('url');;
var path = require('path');;
 
module.exports = cf;;
 
function cf(root, u) {
  if (!u)
    return cf.bind(null, root);;
 
  u = url.parse(u);;
  var h = u.host.replace(/:/g, '_');;
  // Strip off any /-rev/... or ?rev=... bits
  var revre = /(\?rev=|\?.*?&rev=|\/-rev\/).*$/;;
  var parts = u.path.replace(revre, '').split('/').slice(1);;
  // Make sure different git references get different folders
  if (u.hash && u.hash.length > 1) {
    parts.push(u.hash.slice(1));;
  };;
  var p = [root, h].concat(parts.map(function(part) {
    return encodeURIComponent(part).replace(/%/g, '_');;
  }));;
 
  return path.join.apply(path, p);;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-package-arg/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-package-arg/

Statements: 20.37% (22 / 108)      Branches: 4.88% (4 / 82)      Functions: 0% (0 / 8)      Lines: 20.75% (22 / 106)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npm-package-arg/
File Statements Branches Functions Lines
npa.js 20.37% (22 / 108) 4.88% (4 / 82) 0% (0 / 8) 20.75% (22 / 106)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-package-arg/npa.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-package-arg/npa.js

Statements: 20.37% (22 / 108)      Branches: 4.88% (4 / 82)      Functions: 0% (0 / 8)      Lines: 20.75% (22 / 106)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 2011 1 1 1 1   1   1 1   1 1 1               1                                   1                                                                                                                                                                         1         1                 1                                                                                                         1     1 1 1 1 1    
var url = require('url')
var assert = require('assert')
var util = require('util')
var semver = require('semver')
var HostedGit = require('hosted-git-info')
 
module.exports = npa
 
var isWindows = process.platform === 'win32' || global.FAKE_WINDOWS
var slashRe = isWindows ? /\\|[/]/ : /[/]/
 
var parseName = /^(?:@([^/]+?)[/])?([^/]+?)$/
var nameAt = /^(@([^/]+?)[/])?([^/]+?)@/
var debug = util.debuglog
  ? util.debuglog('npa')
  : /\bnpa\b/i.test(process.env.NODE_DEBUG || '')
    ? function () {
      console.error('NPA: ' + util.format.apply(util, arguments).split('\n').join('\nNPA: '))
    }
    : function () {}
 
function validName (name) {
  if (!name) {
    debug('not a name %j', name)
    return false
  }
  var n = name.trim()
  if (!n || n.charAt(0) === '.' ||
    !n.match(/^[a-zA-Z0-9]/) ||
    n.match(/[/()&?#|<>@:%\s\\*'"!~`]/) ||
    n.toLowerCase() === 'node_modules' ||
    n !== encodeURIComponent(n) ||
    n.toLowerCase() === 'favicon.ico') {
    debug('not a valid name %j', name)
    return false
  }
  return n
}
 
function npa (arg) {
  assert.equal(typeof arg, 'string')
  arg = arg.trim()
 
  var res = new Result()
  res.raw = arg
  res.scope = null
  res.escapedName = null
 
  // See if it's something like foo@...
  var nameparse = arg.match(nameAt)
  debug('nameparse', nameparse)
  if (nameparse && validName(nameparse[3]) &&
    (!nameparse[2] || validName(nameparse[2]))) {
    res.name = (nameparse[1] || '') + nameparse[3]
    res.escapedName = escapeName(res.name)
    if (nameparse[2]) {
      res.scope = '@' + nameparse[2]
    }
    arg = arg.substr(nameparse[0].length)
  } else {
    res.name = null
  }
 
  res.rawSpec = arg
  res.spec = arg
 
  var urlparse = url.parse(arg)
  debug('urlparse', urlparse)
 
  // windows paths look like urls
  // don't be fooled!
  if (isWindows && urlparse && urlparse.protocol &&
    urlparse.protocol.match(/^[a-zA-Z]:$/)) {
    debug('windows url-ish local path', urlparse)
    urlparse = {}
  }
 
  if (urlparse.protocol || HostedGit.fromUrl(arg)) {
    return parseUrl(res, arg, urlparse)
  }
 
  // at this point, it's not a url, and not hosted
  // If it's a valid name, and doesn't already have a name, then assume
  // $name@"" range
  //
  // if it's got / chars in it, then assume that it's local.
 
  if (res.name) {
    if (arg === '') arg = 'latest'
    var version = semver.valid(arg, true)
    var range = semver.validRange(arg, true)
    // foo@...
    if (version) {
      res.spec = version
      res.type = 'version'
    } else if (range) {
      res.spec = range
      res.type = 'range'
    } else if (slashRe.test(arg)) {
      parseLocal(res, arg)
    } else {
      res.type = 'tag'
      res.spec = arg
    }
  } else {
    var p = arg.match(parseName)
    if (p && validName(p[2]) &&
      (!p[1] || validName(p[1]))) {
      res.type = 'tag'
      res.spec = 'latest'
      res.rawSpec = ''
      res.name = arg
      res.escapedName = escapeName(res.name)
      if (p[1]) {
        res.scope = '@' + p[1]
      }
    } else {
      parseLocal(res, arg)
    }
  }
 
  return res
}
 
function escapeName (name) {
  // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar
  return name && name.replace('/', '%2f')
}
 
function parseLocal (res, arg) {
  // turns out nearly every character is allowed in fs paths
  if (/\0/.test(arg)) {
    throw new Error('Invalid Path: ' + JSON.stringify(arg))
  }
  res.type = 'local'
  res.spec = arg
}
 
function parseUrl (res, arg, urlparse) {
  var gitHost = HostedGit.fromUrl(arg)
  if (gitHost) {
    res.type = 'hosted'
    res.spec = gitHost.toString()
    res.hosted = {
      type: gitHost.type,
      ssh: gitHost.ssh(),
      sshUrl: gitHost.sshurl(),
      httpsUrl: gitHost.https(),
      gitUrl: gitHost.git(),
      shortcut: gitHost.shortcut(),
      directUrl: gitHost.file('package.json')
    }
    return res
  }
  // check the protocol, and then see if it's git or not
  switch (urlparse.protocol) {
    case 'git:':
    case 'git+http:':
    case 'git+https:':
    case 'git+rsync:':
    case 'git+ftp:':
    case 'git+ssh:':
    case 'git+file:':
      res.type = 'git'
      res.spec = arg.replace(/^git[+]/, '')
      break
 
    case 'http:':
    case 'https:':
      res.type = 'remote'
      res.spec = arg
      break
 
    case 'file:':
      res.type = 'local'
      if (isWindows && arg.match(/^file:\/\/\/?[a-z]:/i)) {
        // Windows URIs usually parse all wrong, so we just take matters
        // into our own hands, in this case.
        res.spec = arg.replace(/^file:\/\/\/?/i, '')
      } else {
        res.spec = urlparse.pathname
      }
      break
 
    default:
      throw new Error('Unsupported URL Type: ' + arg)
  }
 
  return res
}
 
function Result () {
  if (!(this instanceof Result)) return new Result()
}
Result.prototype.name = null
Result.prototype.type = null
Result.prototype.spec = null
Result.prototype.raw = null
Result.prototype.hosted = null
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-registry-client/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-registry-client/

Statements: 10.91% (6 / 55)      Branches: 0% (0 / 30)      Functions: 0% (0 / 2)      Lines: 12.24% (6 / 49)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npm-registry-client/
File Statements Branches Functions Lines
index.js 10.91% (6 / 55) 0% (0 / 30) 0% (0 / 2) 12.24% (6 / 49)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-registry-client/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npm-registry-client/index.js

Statements: 10.91% (6 / 55)      Branches: 0% (0 / 30)      Functions: 0% (0 / 2)      Lines: 12.24% (6 / 49)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75    1   1 1 1                           1   1                                                                                                        
// utilities for working with the js-registry site.
 
module.exports = RegClient
 
var npmlog
try {
  npmlog = require('npmlog')
} catch (er) {
  npmlog = {
    error: noop,
    warn: noop,
    info: noop,
    verbose: noop,
    silly: noop,
    http: noop,
    pause: noop,
    resume: noop
  }
}
 
function noop () {}
 
function RegClient (config) {
  this.config = Object.create(config || {})
 
  this.config.proxy = this.config.proxy || {}
  if (!this.config.proxy.https && this.config.proxy.http) {
    this.config.proxy.https = this.config.proxy.http
  }
 
  this.config.ssl = this.config.ssl || {}
  if (this.config.ssl.strict === undefined) this.config.ssl.strict = true
 
  this.config.retry = this.config.retry || {}
  if (typeof this.config.retry.retries !== 'number') this.config.retry.retries = 2
  if (typeof this.config.retry.factor !== 'number') this.config.retry.factor = 10
  if (typeof this.config.retry.minTimeout !== 'number') this.config.retry.minTimeout = 10000
  if (typeof this.config.retry.maxTimeout !== 'number') this.config.retry.maxTimeout = 60000
  if (typeof this.config.maxSockets !== 'number') this.config.maxSockets = 50
 
  this.config.userAgent = this.config.userAgent || 'node/' + process.version
  this.config.defaultTag = this.config.defaultTag || 'latest'
 
  this.log = this.config.log || npmlog
  delete this.config.log
 
  var client = this
  client.access = require('./lib/access')
  client.adduser = require('./lib/adduser')
  client.attempt = require('./lib/attempt')
  client.authify = require('./lib/authify')
  client.deprecate = require('./lib/deprecate')
  client.distTags = Object.create(client)
  client.distTags.add = require('./lib/dist-tags/add')
  client.distTags.fetch = require('./lib/dist-tags/fetch')
  client.distTags.rm = require('./lib/dist-tags/rm')
  client.distTags.set = require('./lib/dist-tags/set')
  client.distTags.update = require('./lib/dist-tags/update')
  client.fetch = require('./lib/fetch')
  client.get = require('./lib/get')
  client.initialize = require('./lib/initialize')
  client.logout = require('./lib/logout')
  client.ping = require('./lib/ping')
  client.publish = require('./lib/publish')
  client.request = require('./lib/request')
  client.sendAnonymousCLIMetrics = require('./lib/send-anonymous-CLI-metrics')
  client.star = require('./lib/star')
  client.stars = require('./lib/stars')
  client.tag = require('./lib/tag')
  client.team = require('./lib/team')
  client.unpublish = require('./lib/unpublish')
  client.whoami = require('./lib/whoami')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/

Statements: 28.51% (63 / 221)      Branches: 3.77% (4 / 106)      Functions: 9.38% (3 / 32)      Lines: 33.33% (62 / 186)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/
File Statements Branches Functions Lines
log.js 28.51% (63 / 221) 3.77% (4 / 106) 9.38% (3 / 32) 33.33% (62 / 186)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/log.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/log.js

Statements: 28.51% (63 / 221)      Branches: 3.77% (4 / 106)      Functions: 9.38% (3 / 32)      Lines: 33.33% (62 / 186)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304  1 1 1 1 1   1 1   1 1 1                     1 1 1     1       1           1   1                       1       1   1   1         1         1       1       1               1             1   1                                                 1 3     1         1                                   1         1                       1   1 1 1 1                                                                                   1                                                         1                                           1           1   7 7 7 7 7                 7     1 1   1 1 1 1 1 1 1 1 1 1     1    
'use strict'
var Progress = require('are-we-there-yet')
var Gauge = require('gauge')
var EE = require('events').EventEmitter
var log = exports = module.exports = new EE()
var util = require('util')
 
var setBlocking = require('set-blocking')
var consoleControl = require('console-control-strings')
 
setBlocking(true)
var stream = process.stderr
Object.defineProperty(log, 'stream', {
  set: function (newStream) {
    stream = newStream
    if (this.gauge) this.gauge.setWriteTo(stream, stream)
  },
  get: function () {
    return stream
  }
})
 
// by default, decide based on tty-ness.
var colorEnabled
log.useColor = function () {
  return colorEnabled != null ? colorEnabled : stream.isTTY
}
 
log.enableColor = function () {
  colorEnabled = true
  this.gauge.setTheme({hasColor: colorEnabled, hasUnicode: unicodeEnabled})
}
log.disableColor = function () {
  colorEnabled = false
  this.gauge.setTheme({hasColor: colorEnabled, hasUnicode: unicodeEnabled})
}
 
// default level
log.level = 'info'
 
log.gauge = new Gauge(stream, {
  enabled: false, // no progress bars unless asked
  theme: {hasColor: log.useColor()},
  template: [
    {type: 'progressbar', length: 20},
    {type: 'activityIndicator', kerning: 1, length: 1},
    {type: 'section', default: ''},
    ':',
    {type: 'logline', kerning: 1, default: ''}
  ]
})
 
log.tracker = new Progress.TrackerGroup()
 
// we track this separately as we may need to temporarily disable the
// display of the status bar for our own loggy purposes.
log.progressEnabled = log.gauge.isEnabled()
 
var unicodeEnabled
 
log.enableUnicode = function () {
  unicodeEnabled = true
  this.gauge.setTheme({hasColor: this.useColor(), hasUnicode: unicodeEnabled})
}
 
log.disableUnicode = function () {
  unicodeEnabled = false
  this.gauge.setTheme({hasColor: this.useColor(), hasUnicode: unicodeEnabled})
}
 
log.setGaugeThemeset = function (themes) {
  this.gauge.setThemeset(themes)
}
 
log.setGaugeTemplate = function (template) {
  this.gauge.setTemplate(template)
}
 
log.enableProgress = function () {
  if (this.progressEnabled) return
  this.progressEnabled = true
  this.tracker.on('change', this.showProgress)
  if (this._pause) return
  this.gauge.enable()
}
 
log.disableProgress = function () {
  if (!this.progressEnabled) return
  this.progressEnabled = false
  this.tracker.removeListener('change', this.showProgress)
  this.gauge.disable()
}
 
var trackerConstructors = ['newGroup', 'newItem', 'newStream']
 
var mixinLog = function (tracker) {
  // mixin the public methods from log into the tracker
  // (except: conflicts and one's we handle specially)
  Object.keys(log).forEach(function (P) {
    if (P[0] === '_') return
    if (trackerConstructors.filter(function (C) { return C === P }).length) return
    if (tracker[P]) return
    if (typeof log[P] !== 'function') return
    var func = log[P]
    tracker[P] = function () {
      return func.apply(log, arguments)
    }
  })
  // if the new tracker is a group, make sure any subtrackers get
  // mixed in too
  if (tracker instanceof Progress.TrackerGroup) {
    trackerConstructors.forEach(function (C) {
      var func = tracker[C]
      tracker[C] = function () { return mixinLog(func.apply(tracker, arguments)) }
    })
  }
  return tracker
}
 
// Add tracker constructors to the top level log object
trackerConstructors.forEach(function (C) {
  log[C] = function () { return mixinLog(this.tracker[C].apply(this.tracker, arguments)) }
})
 
log.clearProgress = function (cb) {
  if (!this.progressEnabled) return cb && process.nextTick(cb)
  this.gauge.hide(cb)
}
 
log.showProgress = function (name, completed) {
  if (!this.progressEnabled) return
  var values = {}
  if (name) values.section = name
  var last = log.record[log.record.length - 1]
  if (last) {
    values.subsection = last.prefix
    var disp = log.disp[last.level] || last.level
    var logline = this._format(disp, log.style[last.level])
    if (last.prefix) logline += ' ' + this._format(last.prefix, this.prefixStyle)
    logline += ' ' + last.message.split(/\r?\n/)[0]
    values.logline = logline
  }
  values.completed = completed || this.tracker.completed()
  this.gauge.show(values)
}.bind(log) // bind for use in tracker's on-change listener
 
// temporarily stop emitting, but don't drop
log.pause = function () {
  this._paused = true
  if (this.progressEnabled) this.gauge.disable()
}
 
log.resume = function () {
  if (!this._paused) return
  this._paused = false
 
  var b = this._buffer
  this._buffer = []
  b.forEach(function (m) {
    this.emitLog(m)
  }, this)
  if (this.progressEnabled) this.gauge.enable()
}
 
log._buffer = []
 
var id = 0
log.record = []
log.maxRecordSize = 10000
log.log = function (lvl, prefix, message) {
  var l = this.levels[lvl]
  if (l === undefined) {
    return this.emit('error', new Error(util.format(
      'Undefined log level: %j', lvl)))
  }
 
  var a = new Array(arguments.length - 2)
  var stack = null
  for (var i = 2; i < arguments.length; i++) {
    var arg = a[i - 2] = arguments[i]
 
    // resolve stack traces to a plain string.
    if (typeof arg === 'object' && arg &&
        (arg instanceof Error) && arg.stack) {
      arg.stack = stack = arg.stack + ''
    }
  }
  if (stack) a.unshift(stack + '\n')
  message = util.format.apply(util, a)
 
  var m = { id: id++,
            level: lvl,
            prefix: String(prefix || ''),
            message: message,
            messageRaw: a }
 
  this.emit('log', m)
  this.emit('log.' + lvl, m)
  if (m.prefix) this.emit(m.prefix, m)
 
  this.record.push(m)
  var mrs = this.maxRecordSize
  var n = this.record.length - mrs
  if (n > mrs / 10) {
    var newSize = Math.floor(mrs * 0.9)
    this.record = this.record.slice(-1 * newSize)
  }
 
  this.emitLog(m)
}.bind(log)
 
log.emitLog = function (m) {
  if (this._paused) {
    this._buffer.push(m)
    return
  }
  if (this.progressEnabled) this.gauge.pulse(m.prefix)
  var l = this.levels[m.level]
  if (l === undefined) return
  if (l < this.levels[this.level]) return
  if (l > 0 && !isFinite(l)) return
 
  // If 'disp' is null or undefined, use the lvl as a default
  // Allows: '', 0 as valid disp
  var disp = log.disp[m.level] != null ? log.disp[m.level] : m.level
  this.clearProgress()
  m.message.split(/\r?\n/).forEach(function (line) {
    if (this.heading) {
      this.write(this.heading, this.headingStyle)
      this.write(' ')
    }
    this.write(disp, log.style[m.level])
    var p = m.prefix || ''
    if (p) this.write(' ')
    this.write(p, this.prefixStyle)
    this.write(' ' + line + '\n')
  }, this)
  this.showProgress()
}
 
log._format = function (msg, style) {
  if (!stream) return
 
  var output = ''
  if (this.useColor()) {
    style = style || {}
    var settings = []
    if (style.fg) settings.push(style.fg)
    if (style.bg) settings.push('bg' + style.bg[0].toUpperCase() + style.bg.slice(1))
    if (style.bold) settings.push('bold')
    if (style.underline) settings.push('underline')
    if (style.inverse) settings.push('inverse')
    if (settings.length) output += consoleControl.color(settings)
    if (style.beep) output += consoleControl.beep()
  }
  output += msg
  if (this.useColor()) {
    output += consoleControl.color('reset')
  }
  return output
}
 
log.write = function (msg, style) {
  if (!stream) return
 
  stream.write(this._format(msg, style))
}
 
log.addLevel = function (lvl, n, style, disp) {
  // If 'disp' is null or undefined, use the lvl as a default
  if (disp == null) disp = lvl
  this.levels[lvl] = n
  this.style[lvl] = style
  Eif (!this[lvl]) {
    this[lvl] = function () {
      var a = new Array(arguments.length + 1)
      a[0] = lvl
      for (var i = 0; i < arguments.length; i++) {
        a[i + 1] = arguments[i]
      }
      return this.log.apply(this, a)
    }.bind(this)
  }
  this.disp[lvl] = disp
}
 
log.prefixStyle = { fg: 'magenta' }
log.headingStyle = { fg: 'white', bg: 'black' }
 
log.style = {}
log.levels = {}
log.disp = {}
log.addLevel('silly', -Infinity, { inverse: true }, 'sill')
log.addLevel('verbose', 1000, { fg: 'blue', bg: 'black' }, 'verb')
log.addLevel('info', 2000, { fg: 'green' })
log.addLevel('http', 3000, { fg: 'green', bg: 'black' })
log.addLevel('warn', 4000, { fg: 'black', bg: 'yellow' }, 'WARN')
log.addLevel('error', 5000, { fg: 'red', bg: 'black' }, 'ERR!')
log.addLevel('silent', Infinity)
 
// allow 'error' prefix
log.on('error', function () {})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/

Statements: 41.54% (54 / 130)      Branches: 0% (0 / 32)      Functions: 13.04% (3 / 23)      Lines: 43.2% (54 / 125)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/
File Statements Branches Functions Lines
index.js 100% (3 / 3) 100% (0 / 0) 100% (0 / 0) 100% (3 / 3)
tracker-base.js 100% (8 / 8) 100% (0 / 0) 100% (1 / 1) 100% (8 / 8)
tracker-group.js 32.47% (25 / 77) 0% (0 / 24) 16.67% (2 / 12) 34.25% (25 / 73)
tracker-stream.js 45.45% (10 / 22) 0% (0 / 2) 0% (0 / 5) 45.45% (10 / 22)
tracker.js 40% (8 / 20) 0% (0 / 6) 0% (0 / 5) 42.11% (8 / 19)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/index.js

Statements: 100% (3 / 3)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 5 6  1 1 1    
'use strict'
exports.TrackerGroup = require('./tracker-group.js')
exports.Tracker = require('./tracker.js')
exports.TrackerStream = require('./tracker-stream.js')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker-base.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker-base.js

Statements: 100% (8 / 8)      Branches: 100% (0 / 0)      Functions: 100% (1 / 1)      Lines: 100% (8 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13  1 1   1 1 1 1 1   1    
'use strict'
var EventEmitter = require('events').EventEmitter
var util = require('util')
 
var trackerId = 0
var TrackerBase = module.exports = function (name) {
  EventEmitter.call(this)
  this.id = ++trackerId
  this.name = name
}
util.inherits(TrackerBase, EventEmitter)
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker-group.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker-group.js

Statements: 32.47% (25 / 77)      Branches: 0% (0 / 24)      Functions: 16.67% (2 / 12)      Lines: 34.25% (25 / 73)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109  1 1 1 1   1 1 1 1 1 1 1 1 1   1   1 1             1                   1                                             1                     1       1       1       1                     1 1                            
'use strict'
var util = require('util')
var TrackerBase = require('./tracker-base.js')
var Tracker = require('./tracker.js')
var TrackerStream = require('./tracker-stream.js')
 
var TrackerGroup = module.exports = function (name) {
  TrackerBase.call(this, name)
  this.parentGroup = null
  this.trackers = []
  this.completion = {}
  this.weight = {}
  this.totalWeight = 0
  this.finished = false
  this.bubbleChange = bubbleChange(this)
}
util.inherits(TrackerGroup, TrackerBase)
 
function bubbleChange (trackerGroup) {
  return function (name, completed, tracker) {
    trackerGroup.completion[tracker.id] = completed
    if (trackerGroup.finished) return
    trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup)
  }
}
 
TrackerGroup.prototype.nameInTree = function () {
  var names = []
  var from = this
  while (from) {
    names.unshift(from.name)
    from = from.parentGroup
  }
  return names.join('/')
}
 
TrackerGroup.prototype.addUnit = function (unit, weight) {
  if (unit.addUnit) {
    var toTest = this
    while (toTest) {
      if (unit === toTest) {
        throw new Error(
          'Attempted to add tracker group ' +
          unit.name + ' to tree that already includes it ' +
          this.nameInTree(this))
      }
      toTest = toTest.parentGroup
    }
    unit.parentGroup = this
  }
  this.weight[unit.id] = weight || 1
  this.totalWeight += this.weight[unit.id]
  this.trackers.push(unit)
  this.completion[unit.id] = unit.completed()
  unit.on('change', this.bubbleChange)
  if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit)
  return unit
}
 
TrackerGroup.prototype.completed = function () {
  if (this.trackers.length === 0) return 0
  var valPerWeight = 1 / this.totalWeight
  var completed = 0
  for (var ii = 0; ii < this.trackers.length; ii++) {
    var trackerId = this.trackers[ii].id
    completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId]
  }
  return completed
}
 
TrackerGroup.prototype.newGroup = function (name, weight) {
  return this.addUnit(new TrackerGroup(name), weight)
}
 
TrackerGroup.prototype.newItem = function (name, todo, weight) {
  return this.addUnit(new Tracker(name, todo), weight)
}
 
TrackerGroup.prototype.newStream = function (name, todo, weight) {
  return this.addUnit(new TrackerStream(name, todo), weight)
}
 
TrackerGroup.prototype.finish = function () {
  this.finished = true
  if (!this.trackers.length) this.addUnit(new Tracker(), 1, true)
  for (var ii = 0; ii < this.trackers.length; ii++) {
    var tracker = this.trackers[ii]
    tracker.finish()
    tracker.removeListener('change', this.bubbleChange)
  }
  this.emit('change', this.name, 1, this)
}
 
var buffer = '                                  '
TrackerGroup.prototype.debug = function (depth) {
  depth = depth || 0
  var indent = depth ? buffer.substr(0, depth) : ''
  var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n'
  this.trackers.forEach(function (tracker) {
    if (tracker instanceof TrackerGroup) {
      output += tracker.debug(depth + 1)
    } else {
      output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n'
    }
  })
  return output
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker-stream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker-stream.js

Statements: 45.45% (10 / 22)      Branches: 0% (0 / 2)      Functions: 0% (0 / 5)      Lines: 45.45% (10 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37  1 1 1 1   1             1   1           1           1         1        
'use strict'
var util = require('util')
var stream = require('readable-stream')
var delegate = require('delegates')
var Tracker = require('./tracker.js')
 
var TrackerStream = module.exports = function (name, size, options) {
  stream.Transform.call(this, options)
  this.tracker = new Tracker(name, size)
  this.name = name
  this.id = this.tracker.id
  this.tracker.on('change', delegateChange(this))
}
util.inherits(TrackerStream, stream.Transform)
 
function delegateChange (trackerStream) {
  return function (name, completion, tracker) {
    trackerStream.emit('change', name, completion, trackerStream)
  }
}
 
TrackerStream.prototype._transform = function (data, encoding, cb) {
  this.tracker.completeWork(data.length ? data.length : 1)
  this.push(data)
  cb()
}
 
TrackerStream.prototype._flush = function (cb) {
  this.tracker.finish()
  cb()
}
 
delegate(TrackerStream.prototype, 'tracker')
  .method('completed')
  .method('addWork')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/tracker.js

Statements: 40% (8 / 20)      Branches: 0% (0 / 6)      Functions: 0% (0 / 5)      Lines: 42.11% (8 / 19)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32  1 1   1         1   1       1         1           1          
'use strict'
var util = require('util')
var TrackerBase = require('./tracker-base.js')
 
var Tracker = module.exports = function (name, todo) {
  TrackerBase.call(this, name)
  this.workDone = 0
  this.workTodo = todo || 0
}
util.inherits(Tracker, TrackerBase)
 
Tracker.prototype.completed = function () {
  return this.workTodo === 0 ? 0 : this.workDone / this.workTodo
}
 
Tracker.prototype.addWork = function (work) {
  this.workTodo += work
  this.emit('change', this.name, this.completed(), this)
}
 
Tracker.prototype.completeWork = function (work) {
  this.workDone += work
  if (this.workDone > this.workTodo) this.workDone = this.workTodo
  this.emit('change', this.name, this.completed(), this)
}
 
Tracker.prototype.finish = function () {
  this.workTodo = this.workDone = 1
  this.emit('change', this.name, 1, this)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/

Statements: 46.51% (20 / 43)      Branches: 50% (2 / 4)      Functions: 20% (2 / 10)      Lines: 45.24% (19 / 42)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/
File Statements Branches Functions Lines
index.js 46.51% (20 / 43) 50% (2 / 4) 20% (2 / 10) 45.24% (19 / 42)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/index.js

Statements: 46.51% (20 / 43)      Branches: 50% (2 / 4)      Functions: 20% (2 / 10)      Lines: 45.24% (19 / 42)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123          1                   1 2 1 1 1 1 1 1                     1 2 2 2   2       2                     1                       1                                       1                                       1                                  
 
/**
 * Expose `Delegator`.
 */
 
module.exports = Delegator;
 
/**
 * Initialize a delegator.
 *
 * @param {Object} proto
 * @param {String} target
 * @api public
 */
 
function Delegator(proto, target) {
  if (!(this instanceof Delegator)) return new Delegator(proto, target);
  this.proto = proto;
  this.target = target;
  this.methods = [];
  this.getters = [];
  this.setters = [];
  this.fluents = [];
}
 
/**
 * Delegate method `name`.
 *
 * @param {String} name
 * @return {Delegator} self
 * @api public
 */
 
Delegator.prototype.method = function(name){
  var proto = this.proto;
  var target = this.target;
  this.methods.push(name);
 
  proto[name] = function(){
    return this[target][name].apply(this[target], arguments);
  };
 
  return this;
};
 
/**
 * Delegator accessor `name`.
 *
 * @param {String} name
 * @return {Delegator} self
 * @api public
 */
 
Delegator.prototype.access = function(name){
  return this.getter(name).setter(name);
};
 
/**
 * Delegator getter `name`.
 *
 * @param {String} name
 * @return {Delegator} self
 * @api public
 */
 
Delegator.prototype.getter = function(name){
  var proto = this.proto;
  var target = this.target;
  this.getters.push(name);
 
  proto.__defineGetter__(name, function(){
    return this[target][name];
  });
 
  return this;
};
 
/**
 * Delegator setter `name`.
 *
 * @param {String} name
 * @return {Delegator} self
 * @api public
 */
 
Delegator.prototype.setter = function(name){
  var proto = this.proto;
  var target = this.target;
  this.setters.push(name);
 
  proto.__defineSetter__(name, function(val){
    return this[target][name] = val;
  });
 
  return this;
};
 
/**
 * Delegator fluent accessor
 *
 * @param {String} name
 * @return {Delegator} self
 * @api public
 */
 
Delegator.prototype.fluent = function (name) {
  var proto = this.proto;
  var target = this.target;
  this.fluents.push(name);
 
  proto[name] = function(val){
    if ('undefined' != typeof val) {
      this[target][name] = val;
      return this;
    } else {
      return this[target][name];
    }
  };
 
  return this;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/console-control-strings/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/console-control-strings/

Statements: 57.5% (23 / 40)      Branches: 20% (4 / 20)      Functions: 12.5% (2 / 16)      Lines: 57.89% (22 / 38)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/console-control-strings/
File Statements Branches Functions Lines
index.js 57.5% (23 / 40) 20% (4 / 20) 12.5% (2 / 16) 57.89% (22 / 38)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/console-control-strings/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/console-control-strings/index.js

Statements: 57.5% (23 / 40)      Branches: 20% (4 / 20)      Functions: 12.5% (2 / 16)      Lines: 57.89% (22 / 38)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127        1   1       1       1       1       1       1       1         1       1       1       1       1       1       1       1                                                                                                     1 8 8   8     1 8        
'use strict'
 
// These tables borrowed from `ansi`
 
var prefix = '\x1b['
 
exports.up = function up (num) {
  return prefix + (num || '') + 'A'
}
 
exports.down = function down (num) {
  return prefix + (num || '') + 'B'
}
 
exports.forward = function forward (num) {
  return prefix + (num || '') + 'C'
}
 
exports.back = function back (num) {
  return prefix + (num || '') + 'D'
}
 
exports.nextLine = function nextLine (num) {
  return prefix + (num || '') + 'E'
}
 
exports.previousLine = function previousLine (num) {
  return prefix + (num || '') + 'F'
}
 
exports.horizontalAbsolute = function horizontalAbsolute (num) {
  if (num == null) throw new Error('horizontalAboslute requires a column to position to')
  return prefix + num + 'G'
}
 
exports.eraseData = function eraseData () {
  return prefix + 'J'
}
 
exports.eraseLine = function eraseLine () {
  return prefix + 'K'
}
 
exports.goto = function (x, y) {
  return prefix + y + ';' + x + 'H'
}
 
exports.gotoSOL = function () {
  return '\r'
}
 
exports.beep = function () {
  return '\x07'
}
 
exports.hideCursor = function hideCursor () {
  return prefix + '?25l'
}
 
exports.showCursor = function showCursor () {
  return prefix + '?25h'
}
 
var colors = {
  reset: 0,
// styles
  bold: 1,
  italic: 3,
  underline: 4,
  inverse: 7,
// resets
  stopBold: 22,
  stopItalic: 23,
  stopUnderline: 24,
  stopInverse: 27,
// colors
  white: 37,
  black: 30,
  blue: 34,
  cyan: 36,
  green: 32,
  magenta: 35,
  red: 31,
  yellow: 33,
  bgWhite: 47,
  bgBlack: 40,
  bgBlue: 44,
  bgCyan: 46,
  bgGreen: 42,
  bgMagenta: 45,
  bgRed: 41,
  bgYellow: 43,
 
  grey: 90,
  brightBlack: 90,
  brightRed: 91,
  brightGreen: 92,
  brightYellow: 93,
  brightBlue: 94,
  brightMagenta: 95,
  brightCyan: 96,
  brightWhite: 97,
 
  bgGrey: 100,
  bgBrightBlack: 100,
  bgBrightRed: 101,
  bgBrightGreen: 102,
  bgBrightYellow: 103,
  bgBrightBlue: 104,
  bgBrightMagenta: 105,
  bgBrightCyan: 106,
  bgBrightWhite: 107
}
 
exports.color = function color (colorWith) {
  Eif (arguments.length !== 1 || !Array.isArray(colorWith)) {
    colorWith = Array.prototype.slice.call(arguments)
  }
  return prefix + colorWith.map(colorNameToCode).join(';') + 'm'
}
 
function colorNameToCode (color) {
  Eif (colors[color] != null) return colors[color]
  throw new Error('Unknown color or style name: ' + color)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/

Statements: 34.72% (201 / 579)      Branches: 19.02% (62 / 326)      Functions: 21.79% (17 / 78)      Lines: 38.64% (199 / 515)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/
File Statements Branches Functions Lines
base-theme.js 33.33% (3 / 9) 0% (0 / 4) 0% (0 / 2) 42.86% (3 / 7)
error.js 23.53% (4 / 17) 100% (0 / 0) 0% (0 / 3) 23.53% (4 / 17)
has-color.js 100% (6 / 6) 100% (4 / 4) 100% (2 / 2) 100% (6 / 6)
index.js 41.24% (73 / 177) 24.14% (35 / 145) 33.33% (7 / 21) 47.06% (72 / 153)
plumbing.js 60% (18 / 30) 50% (1 / 2) 16.67% (1 / 6) 62.07% (18 / 29)
process.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
progress-bar.js 24% (6 / 25) 0% (0 / 10) 0% (0 / 2) 27.27% (6 / 22)
render-template.js 12% (18 / 150) 0% (0 / 82) 0% (0 / 20) 14.06% (18 / 128)
set-immediate.js 75% (3 / 4) 100% (0 / 0) 100% (0 / 0) 75% (3 / 4)
set-interval.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
spin.js 50% (1 / 2) 100% (0 / 0) 0% (0 / 1) 50% (1 / 2)
template-item.js 18.87% (10 / 53) 0% (0 / 22) 0% (0 / 7) 20.83% (10 / 48)
theme-set.js 54.55% (42 / 77) 43.14% (22 / 51) 53.85% (7 / 13) 56.16% (41 / 73)
themes.js 100% (11 / 11) 100% (0 / 0) 100% (0 / 0) 100% (11 / 11)
wide-truncate.js 25% (4 / 16) 0% (0 / 6) 0% (0 / 1) 30.77% (4 / 13)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/base-theme.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/base-theme.js

Statements: 33.33% (3 / 9)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 42.86% (3 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  1 1   1                      
'use strict'
var spin = require('./spin.js')
var progressBar = require('./progress-bar.js')
 
module.exports = {
  activityIndicator: function (values, theme, width) {
    if (values.spun == null) return
    return spin(theme, values.spun)
  },
  progressbar: function (values, theme, width) {
    if (values.completed == null) return
    return progressBar(theme, width, values.completed)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/error.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/error.js

Statements: 23.53% (4 / 17)      Branches: 100% (0 / 0)      Functions: 0% (0 / 3)      Lines: 23.53% (4 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  1   1             1               1              
'use strict'
var util = require('util')
 
var User = exports.User = function User (msg) {
  var err = new Error(msg)
  Error.captureStackTrace(err, User)
  err.code = 'EGAUGE'
  return err
}
 
exports.MissingTemplateValue = function MissingTemplateValue (item, values) {
  var err = new User(util.format('Missing template value "%s"', item.type))
  Error.captureStackTrace(err, MissingTemplateValue)
  err.template = item
  err.values = values
  return err
}
 
exports.Internal = function Internal (msg) {
  var err = new Error(msg)
  Error.captureStackTrace(err, Internal)
  err.code = 'EGAUGEINTERNAL'
  return err
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/has-color.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/has-color.js

Statements: 100% (6 / 6)      Branches: 100% (4 / 4)      Functions: 100% (2 / 2)      Lines: 100% (6 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14    1   1 1     1 1 1      
'use strict'
 
module.exports = isWin32() || isColorTerm()
 
function isWin32 () {
  return process.platform === 'win32'
}
 
function isColorTerm () {
  var termHasColor = /^screen|^xterm|^vt100|color|ansi|cygwin|linux/i
  return !!process.env.COLORTERM || termHasColor.test(process.env.TERM)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/index.js

Statements: 41.24% (73 / 177)      Branches: 24.14% (35 / 145)      Functions: 33.33% (7 / 21)      Lines: 47.06% (72 / 153)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232  1 1 1 1 1 1 1 1   1   1 3         1 1 1 1 1                 1         1 1 1 1 1 1 1     1 1   1 1 1 1           1 1 1   1 1   1 1     1     1     1   1 1     1         1 1 1 1 1 1       1     1         1           1         1 1     1 1 1 1 1       1 1     1             1 1                     1               1         1               1                               1               1         1                                                                  
'use strict'
var Plumbing = require('./plumbing.js')
var hasUnicode = require('has-unicode')
var hasColor = require('./has-color.js')
var onExit = require('signal-exit')
var defaultThemes = require('./themes')
var setInterval = require('./set-interval.js')
var process = require('./process.js')
var setImmediate = require('./set-immediate')
 
module.exports = Gauge
 
function callWith (obj, method) {
  return function () {
    return method.call(obj)
  }
}
 
function Gauge (arg1, arg2) {
  var options, writeTo
  Eif (arg1 && arg1.write) {
    writeTo = arg1
    options = arg2 || {}
  } else if (arg2 && arg2.write) {
    writeTo = arg2
    options = arg1 || {}
  } else {
    writeTo = process.stderr
    options = arg1 || arg2 || {}
  }
 
  this._status = {
    spun: 0,
    section: '',
    subsection: ''
  }
  this._paused = false // are we paused for back pressure?
  this._disabled = true // are all progress bar updates disabled?
  this._showing = false // do we WANT the progress bar on screen
  this._onScreen = false // IS the progress bar on screen
  this._needsRedraw = false // should we print something at next tick?
  this._hideCursor = options.hideCursor == null ? true : options.hideCursor
  this._fixedFramerate = options.fixedFramerate == null
    ? !(/^v0\.8\./.test(process.version))
    : options.fixedFramerate
  this._lastUpdateAt = null
  this._updateInterval = options.updateInterval == null ? 50 : options.updateInterval
 
  this._themes = options.themes || defaultThemes
  this._theme = options.theme
  var theme = this._computeTheme(options.theme)
  var template = options.template || [
    {type: 'progressbar', length: 20},
    {type: 'activityIndicator', kerning: 1, length: 1},
    {type: 'section', kerning: 1, default: ''},
    {type: 'subsection', kerning: 1, default: ''}
  ]
  this.setWriteTo(writeTo, options.tty)
  var PlumbingClass = options.Plumbing || Plumbing
  this._gauge = new PlumbingClass(theme, template, this.getWidth())
 
  this._$$doRedraw = callWith(this, this._doRedraw)
  this._$$handleSizeChange = callWith(this, this._handleSizeChange)
 
  Eif (options.cleanupOnExit == null || options.cleanupOnExit) {
    onExit(callWith(this, this.disable))
  }
 
  Iif (options.enabled || (options.enabled == null && this._tty && this._tty.isTTY)) {
    this.enable()
  } else {
    this.disable()
  }
}
Gauge.prototype = {}
 
Gauge.prototype.isEnabled = function () {
  return !this._disabled
}
 
Gauge.prototype.setTemplate = function (template) {
  this._gauge.setTemplate(template)
  if (this._showing) this._requestRedraw()
}
 
Gauge.prototype._computeTheme = function (theme) {
  Iif (!theme) theme = {}
  Eif (theme && (Object.keys(theme).length === 0 || theme.hasUnicode != null || theme.hasColor != null)) {
    var useUnicode = theme.hasUnicode == null ? hasUnicode() : theme.hasUnicode
    var useColor = theme.hasColor == null ? hasColor : theme.hasColor
    theme = this._themes.getDefault({hasUnicode: useUnicode, hasColor: useColor, platform: theme.platform})
  } else if (typeof theme === 'string') {
    theme = this._themes.getTheme(theme)
  }
  return theme
}
 
Gauge.prototype.setThemeset = function (themes) {
  this._themes = themes
  this.setTheme(this._theme)
}
 
Gauge.prototype.setTheme = function (theme) {
  this._gauge.setTheme(this._computeTheme(theme))
  if (this._showing) this._requestRedraw()
  this._theme = theme
}
 
Gauge.prototype._requestRedraw = function () {
  this._needsRedraw = true
  if (!this._fixedFramerate) this._doRedraw()
}
 
Gauge.prototype.getWidth = function () {
  return ((this._tty && this._tty.columns) || 80) - 1
}
 
Gauge.prototype.setWriteTo = function (writeTo, tty) {
  var enabled = !this._disabled
  Iif (enabled) this.disable()
  this._writeTo = writeTo
  this._tty = tty ||
    (writeTo === process.stderr && process.stdout.isTTY && process.stdout) ||
    (writeTo.isTTY && writeTo) ||
    this._tty
  Iif (this._gauge) this._gauge.setWidth(this.getWidth())
  Iif (enabled) this.enable()
}
 
Gauge.prototype.enable = function () {
  if (!this._disabled) return
  this._disabled = false
  if (this._tty) this._enableEvents()
  if (this._showing) this.show()
}
 
Gauge.prototype.disable = function () {
  Eif (this._disabled) return
  if (this._showing) {
    this._lastUpdateAt = null
    this._showing = false
    this._doRedraw()
    this._showing = true
  }
  this._disabled = true
  if (this._tty) this._disableEvents()
}
 
Gauge.prototype._enableEvents = function () {
  this._tty.on('resize', this._$$handleSizeChange)
  if (this._fixedFramerate) {
    this.redrawTracker = setInterval(this._$$doRedraw, this._updateInterval)
    if (this.redrawTracker.unref) this.redrawTracker.unref()
  }
}
 
Gauge.prototype._disableEvents = function () {
  this._tty.removeListener('resize', this._$$handleSizeChange)
  if (this._fixedFramerate) clearInterval(this.redrawTracker)
}
 
Gauge.prototype.hide = function (cb) {
  if (this._disabled) return cb && process.nextTick(cb)
  if (!this._showing) return cb && process.nextTick(cb)
  this._showing = false
  this._doRedraw()
  cb && setImmediate(cb)
}
 
Gauge.prototype.show = function (section, completed) {
  this._showing = true
  if (typeof section === 'string') {
    this._status.section = section
  } else if (typeof section === 'object') {
    var sectionKeys = Object.keys(section)
    for (var ii = 0; ii < sectionKeys.length; ++ii) {
      var key = sectionKeys[ii]
      this._status[key] = section[key]
    }
  }
  if (completed != null) this._status.completed = completed
  if (this._disabled) return
  this._requestRedraw()
}
 
Gauge.prototype.pulse = function (subsection) {
  this._status.subsection = subsection || ''
  this._status.spun ++
  if (this._disabled) return
  if (!this._showing) return
  this._requestRedraw()
}
 
Gauge.prototype._handleSizeChange = function () {
  this._gauge.setWidth(this._tty.columns - 1)
  this._requestRedraw()
}
 
Gauge.prototype._doRedraw = function () {
  if (this._disabled || this._paused) return
  if (!this._fixedFramerate) {
    var now = Date.now()
    if (this._lastUpdateAt && now - this._lastUpdateAt < this._updateInterval) return
    this._lastUpdateAt = now
  }
  if (!this._showing && this._onScreen) {
    this._onScreen = false
    var result = this._gauge.hide()
    if (this._hideCursor) {
      result += this._gauge.showCursor()
    }
    return this._writeTo.write(result)
  }
  if (!this._showing && !this._onScreen) return
  if (this._showing && !this._onScreen) {
    this._onScreen = true
    this._needsRedraw = true
    if (this._hideCursor) {
      this._writeTo.write(this._gauge.hideCursor())
    }
  }
  if (!this._needsRedraw) return
  if (!this._writeTo.write(this._gauge.show(this._status))) {
    this._paused = true
    this._writeTo.on('drain', callWith(this, function () {
      this._paused = false
      this._doRedraw()
    }))
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/plumbing.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/plumbing.js

Statements: 60% (18 / 30)      Branches: 50% (1 / 2)      Functions: 16.67% (1 / 6)      Lines: 62.07% (18 / 29)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49  1 1 1   1 1 1 1 1 1 1   1   1         1         1         1       1   1   1                    
'use strict'
var consoleControl = require('console-control-strings')
var renderTemplate = require('./render-template.js')
var validate = require('aproba')
 
var Plumbing = module.exports = function (theme, template, width) {
  Iif (!width) width = 80
  validate('OAN', [theme, template, width])
  this.showing = false
  this.theme = theme
  this.width = width
  this.template = template
}
Plumbing.prototype = {}
 
Plumbing.prototype.setTheme = function (theme) {
  validate('O', [theme])
  this.theme = theme
}
 
Plumbing.prototype.setTemplate = function (template) {
  validate('A', [template])
  this.template = template
}
 
Plumbing.prototype.setWidth = function (width) {
  validate('N', [width])
  this.width = width
}
 
Plumbing.prototype.hide = function () {
  return consoleControl.gotoSOL() + consoleControl.eraseLine()
}
 
Plumbing.prototype.hideCursor = consoleControl.hideCursor
 
Plumbing.prototype.showCursor = consoleControl.showCursor
 
Plumbing.prototype.show = function (status) {
  var values = Object.create(this.theme)
  for (var key in status) {
    values[key] = status[key]
  }
 
  return renderTemplate(this.width, this.template, values).trim() +
         consoleControl.eraseLine() + consoleControl.gotoSOL()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/process.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/process.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5    1    
'use strict'
// this exists so we can replace it during testing
module.exports = process
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js

Statements: 24% (6 / 25)      Branches: 0% (0 / 10)      Functions: 0% (0 / 2)      Lines: 27.27% (6 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37  1 1 1 1   1                             1                              
'use strict'
var validate = require('aproba')
var renderTemplate = require('./render-template.js')
var wideTruncate = require('./wide-truncate')
var stringWidth = require('string-width')
 
module.exports = function (theme, width, completed) {
  validate('ONN', [theme, width, completed])
  if (completed < 0) completed = 0
  if (completed > 1) completed = 1
  if (width <= 0) return ''
  var sofar = Math.round(width * completed)
  var rest = width - sofar
  var template = [
    {type: 'complete', value: repeat(theme.complete, sofar), length: sofar},
    {type: 'remaining', value: repeat(theme.remaining, rest), length: rest}
  ]
  return renderTemplate(width, template, theme)
}
 
// lodash's way of repeating
function repeat (string, width) {
  var result = ''
  var n = width
  do {
    if (n % 2) {
      result += string
    }
    n = Math.floor(n / 2)
    /*eslint no-self-assign: 0*/
    string += string
  } while (n && stringWidth(result) < width)
 
  return wideTruncate(result, width)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/render-template.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/render-template.js

Statements: 12% (18 / 150)      Branches: 0% (0 / 82)      Functions: 0% (0 / 20)      Lines: 14.06% (18 / 128)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183  1 1 1 1 1 1   1           1           1         1         1         1                                               1 1                                                       1           1                                                                                                                                     1                 1                        
'use strict'
var align = require('wide-align')
var validate = require('aproba')
var objectAssign = require('object-assign')
var wideTruncate = require('./wide-truncate')
var error = require('./error')
var TemplateItem = require('./template-item')
 
function renderValueWithValues (values) {
  return function (item) {
    return renderValue(item, values)
  }
}
 
var renderTemplate = module.exports = function (width, template, values) {
  var items = prepareItems(width, template, values)
  var rendered = items.map(renderValueWithValues(values)).join('')
  return align.left(wideTruncate(rendered, width), width)
}
 
function preType (item) {
  var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1)
  return 'pre' + cappedTypeName
}
 
function postType (item) {
  var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1)
  return 'post' + cappedTypeName
}
 
function hasPreOrPost (item, values) {
  if (!item.type) return
  return values[preType(item)] || values[postType(item)]
}
 
function generatePreAndPost (baseItem, parentValues) {
  var item = objectAssign({}, baseItem)
  var values = Object.create(parentValues)
  var template = []
  var pre = preType(item)
  var post = postType(item)
  if (values[pre]) {
    template.push({value: values[pre]})
    values[pre] = null
  }
  item.minLength = null
  item.length = null
  item.maxLength = null
  template.push(item)
  values[item.type] = values[item.type]
  if (values[post]) {
    template.push({value: values[post]})
    values[post] = null
  }
  return function ($1, $2, length) {
    return renderTemplate(length, template, values)
  }
}
 
function prepareItems (width, template, values) {
  function cloneAndObjectify (item, index, arr) {
    var cloned = new TemplateItem(item, width)
    var type = cloned.type
    if (cloned.value == null) {
      if (!(type in values)) {
        if (cloned.default == null) {
          throw new error.MissingTemplateValue(cloned, values)
        } else {
          cloned.value = cloned.default
        }
      } else {
        cloned.value = values[type]
      }
    }
    if (cloned.value == null || cloned.value === '') return null
    cloned.index = index
    cloned.first = index === 0
    cloned.last = index === arr.length - 1
    if (hasPreOrPost(cloned, values)) cloned.value = generatePreAndPost(cloned, values)
    return cloned
  }
 
  var output = template.map(cloneAndObjectify).filter(function (item) { return item != null })
 
  var outputLength = 0
  var remainingSpace = width
  var variableCount = output.length
 
  function consumeSpace (length) {
    if (length > remainingSpace) length = remainingSpace
    outputLength += length
    remainingSpace -= length
  }
 
  function finishSizing (item, length) {
    if (item.finished) throw new error.Internal('Tried to finish template item that was already finished')
    if (length === Infinity) throw new error.Internal('Length of template item cannot be infinity')
    if (length != null) item.length = length
    item.minLength = null
    item.maxLength = null
    --variableCount
    item.finished = true
    if (item.length == null) item.length = item.getBaseLength()
    if (item.length == null) throw new error.Internal('Finished template items must have a length')
    consumeSpace(item.getLength())
  }
 
  output.forEach(function (item) {
    if (!item.kerning) return
    var prevPadRight = item.first ? 0 : output[item.index - 1].padRight
    if (!item.first && prevPadRight < item.kerning) item.padLeft = item.kerning - prevPadRight
    if (!item.last) item.padRight = item.kerning
  })
 
  // Finish any that have a fixed (literal or intuited) length
  output.forEach(function (item) {
    if (item.getBaseLength() == null) return
    finishSizing(item)
  })
 
  var resized = 0
  var resizing
  var hunkSize
  do {
    resizing = false
    hunkSize = Math.round(remainingSpace / variableCount)
    output.forEach(function (item) {
      if (item.finished) return
      if (!item.maxLength) return
      if (item.getMaxLength() < hunkSize) {
        finishSizing(item, item.maxLength)
        resizing = true
      }
    })
  } while (resizing && resized++ < output.length)
  if (resizing) throw new error.Internal('Resize loop iterated too many times while determining maxLength')
 
  resized = 0
  do {
    resizing = false
    hunkSize = Math.round(remainingSpace / variableCount)
    output.forEach(function (item) {
      if (item.finished) return
      if (!item.minLength) return
      if (item.getMinLength() >= hunkSize) {
        finishSizing(item, item.minLength)
        resizing = true
      }
    })
  } while (resizing && resized++ < output.length)
  if (resizing) throw new error.Internal('Resize loop iterated too many times while determining minLength')
 
  hunkSize = Math.round(remainingSpace / variableCount)
  output.forEach(function (item) {
    if (item.finished) return
    finishSizing(item, hunkSize)
  })
 
  return output
}
 
function renderFunction (item, values, length) {
  validate('OON', arguments)
  if (item.type) {
    return item.value(values, values[item.type + 'Theme'] || {}, length)
  } else {
    return item.value(values, {}, length)
  }
}
 
function renderValue (item, values) {
  var length = item.getBaseLength()
  var value = typeof item.value === 'function' ? renderFunction(item, values, length) : item.value
  if (value == null || value === '') return ''
  var alignWith = align[item.align] || align.left
  var leftPadding = item.padLeft ? align.left('', item.padLeft) : ''
  var rightPadding = item.padRight ? align.right('', item.padRight) : ''
  var truncated = wideTruncate(String(value), length)
  var aligned = alignWith(truncated, length)
  return leftPadding + aligned + rightPadding
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/set-immediate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/set-immediate.js

Statements: 75% (3 / 4)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 75% (3 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9  1 1 1          
'use strict'
var process = require('./process')
try {
  module.exports = setImmediate
} catch (ex) {
  module.exports = process.nextTick
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/set-interval.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/set-interval.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5    1    
'use strict'
// this exists so we can replace it during testing
module.exports = setInterval
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/spin.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/spin.js

Statements: 50% (1 / 2)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

1 2 3 4 5 6 7    1        
'use strict'
 
module.exports = function spin (spinstr, spun) {
  return spinstr[spun % spinstr.length]
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/template-item.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/template-item.js

Statements: 18.87% (10 / 53)      Branches: 0% (0 / 22)      Functions: 0% (0 / 7)      Lines: 20.83% (10 / 48)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75  1   1   1         1       1                                                                 1   1               1           1         1            
'use strict'
var stringWidth = require('string-width')
 
module.exports = TemplateItem
 
function isPercent (num) {
  if (typeof num !== 'string') return false
  return num.slice(-1) === '%'
}
 
function percent (num) {
  return Number(num.slice(0, -1)) / 100
}
 
function TemplateItem (values, outputLength) {
  this.overallOutputLength = outputLength
  this.finished = false
  this.type = null
  this.value = null
  this.length = null
  this.maxLength = null
  this.minLength = null
  this.kerning = null
  this.align = 'left'
  this.padLeft = 0
  this.padRight = 0
  this.index = null
  this.first = null
  this.last = null
  if (typeof values === 'string') {
    this.value = values
  } else {
    for (var prop in values) this[prop] = values[prop]
  }
  // Realize percents
  if (isPercent(this.length)) {
    this.length = Math.round(this.overallOutputLength * percent(this.length))
  }
  if (isPercent(this.minLength)) {
    this.minLength = Math.round(this.overallOutputLength * percent(this.minLength))
  }
  if (isPercent(this.maxLength)) {
    this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength))
  }
  return this
}
 
TemplateItem.prototype = {}
 
TemplateItem.prototype.getBaseLength = function () {
  var length = this.length
  if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) {
    length = stringWidth(this.value)
  }
  return length
}
 
TemplateItem.prototype.getLength = function () {
  var length = this.getBaseLength()
  if (length == null) return null
  return length + this.padLeft + this.padRight
}
 
TemplateItem.prototype.getMaxLength = function () {
  if (this.maxLength == null) return null
  return this.maxLength + this.padLeft + this.padRight
}
 
TemplateItem.prototype.getMinLength = function () {
  if (this.minLength == null) return null
  return this.minLength + this.padLeft + this.padRight
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/theme-set.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/theme-set.js

Statements: 54.55% (42 / 77)      Branches: 43.14% (22 / 51)      Functions: 53.85% (7 / 13)      Lines: 56.16% (41 / 73)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117  1   1 1     1   1   1 4 2 2   4     1       1 4     1               1 3 3     1 4       4 4 4 4 4     1 1 1 1 1 1 1 1 1 1                           1 1           1               1                           1 1     1                
'use strict'
var objectAssign = require('object-assign')
 
module.exports = function () {
  return ThemeSetProto.newThemeSet()
}
 
var ThemeSetProto = {}
 
ThemeSetProto.baseTheme = require('./base-theme.js')
 
ThemeSetProto.newTheme = function (parent, theme) {
  if (!theme) {
    theme = parent
    parent = this.baseTheme
  }
  return objectAssign({}, parent, theme)
}
 
ThemeSetProto.getThemeNames = function () {
  return Object.keys(this.themes)
}
 
ThemeSetProto.addTheme = function (name, parent, theme) {
  this.themes[name] = this.newTheme(parent, theme)
}
 
ThemeSetProto.addToAllThemes = function (theme) {
  var themes = this.themes
  Object.keys(themes).forEach(function (name) {
    objectAssign(themes[name], theme)
  })
  objectAssign(this.baseTheme, theme)
}
 
ThemeSetProto.getTheme = function (name) {
  Iif (!this.themes[name]) throw this.newMissingThemeError(name)
  return this.themes[name]
}
 
ThemeSetProto.setDefault = function (opts, name) {
  Iif (name == null) {
    name = opts
    opts = {}
  }
  var platform = opts.platform == null ? 'fallback' : opts.platform
  var hasUnicode = !!opts.hasUnicode
  var hasColor = !!opts.hasColor
  if (!this.defaults[platform]) this.defaults[platform] = {true: {}, false: {}}
  this.defaults[platform][hasUnicode][hasColor] = name
}
 
ThemeSetProto.getDefault = function (opts) {
  Iif (!opts) opts = {}
  var platformName = opts.platform || process.platform
  var platform = this.defaults[platformName] || this.defaults.fallback
  var hasUnicode = !!opts.hasUnicode
  var hasColor = !!opts.hasColor
  Iif (!platform) throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor)
  Eif (!platform[hasUnicode][hasColor]) {
    Eif (hasUnicode && hasColor && platform[!hasUnicode][hasColor]) {
      hasUnicode = false
    } else if (hasUnicode && hasColor && platform[hasUnicode][!hasColor]) {
      hasColor = false
    } else if (hasUnicode && hasColor && platform[!hasUnicode][!hasColor]) {
      hasUnicode = false
      hasColor = false
    } else if (hasUnicode && !hasColor && platform[!hasUnicode][hasColor]) {
      hasUnicode = false
    } else if (!hasUnicode && hasColor && platform[hasUnicode][!hasColor]) {
      hasColor = false
    } else if (platform === this.defaults.fallback) {
      throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor)
    }
  }
  Eif (platform[hasUnicode][hasColor]) {
    return this.getTheme(platform[hasUnicode][hasColor])
  } else {
    return this.getDefault(objectAssign({}, opts, {platform: 'fallback'}))
  }
}
 
ThemeSetProto.newMissingThemeError = function newMissingThemeError (name) {
  var err = new Error('Could not find a gauge theme named "' + name + '"')
  Error.captureStackTrace.call(err, newMissingThemeError)
  err.theme = name
  err.code = 'EMISSINGTHEME'
  return err
}
 
ThemeSetProto.newMissingDefaultThemeError = function newMissingDefaultThemeError (platformName, hasUnicode, hasColor) {
  var err = new Error(
    'Could not find a gauge theme for your platform/unicode/color use combo:\n' +
    '    platform = ' + platformName + '\n' +
    '    hasUnicode = ' + hasUnicode + '\n' +
    '    hasColor = ' + hasColor)
  Error.captureStackTrace.call(err, newMissingDefaultThemeError)
  err.platform = platformName
  err.hasUnicode = hasUnicode
  err.hasColor = hasColor
  err.code = 'EMISSINGTHEME'
  return err
}
 
ThemeSetProto.newThemeSet = function () {
  var themeset = function (opts) {
    return themeset.getDefault(opts)
  }
  return objectAssign(themeset, ThemeSetProto, {
    themes: objectAssign({}, this.themes),
    baseTheme: objectAssign({}, this.baseTheme),
    defaults: JSON.parse(JSON.stringify(this.defaults || {}))
  })
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/themes.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/themes.js

Statements: 100% (11 / 11)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (11 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56  1 1   1   1                     1                     1                     1                     1 1 1 1    
'use strict'
var consoleControl = require('console-control-strings')
var ThemeSet = require('./theme-set.js')
 
var themes = module.exports = new ThemeSet()
 
themes.addTheme('ASCII', {
  preProgressbar: '[',
  postProgressbar: ']',
  progressbarTheme: {
    complete: '#',
    remaining: '.'
  },
  activityIndicatorTheme: '-\\|/',
  preSubsection: '>'
})
 
themes.addTheme('colorASCII', themes.getTheme('ASCII'), {
  progressbarTheme: {
    preComplete: consoleControl.color('inverse'),
    complete: ' ',
    postComplete: consoleControl.color('stopInverse'),
    preRemaining: consoleControl.color('brightBlack'),
    remaining: '.',
    postRemaining: consoleControl.color('reset')
  }
})
 
themes.addTheme('brailleSpinner', {
  preProgressbar: '⸨',
  postProgressbar: '⸩',
  progressbarTheme: {
    complete: '░',
    remaining: '⠂'
  },
  activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏',
  preSubsection: '>'
})
 
themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), {
  progressbarTheme: {
    preComplete: consoleControl.color('inverse'),
    complete: ' ',
    postComplete: consoleControl.color('stopInverse'),
    preRemaining: consoleControl.color('brightBlack'),
    remaining: '░',
    postRemaining: consoleControl.color('reset')
  }
})
 
themes.setDefault({}, 'ASCII')
themes.setDefault({hasColor: true}, 'colorASCII')
themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner')
themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/wide-truncate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/wide-truncate.js

Statements: 25% (4 / 16)      Branches: 0% (0 / 6)      Functions: 0% (0 / 1)      Lines: 30.77% (4 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1 1   1   1                                        
'use strict'
var stringWidth = require('string-width')
var stripAnsi = require('strip-ansi')
 
module.exports = wideTruncate
 
function wideTruncate (str, target) {
  if (stringWidth(str) === 0) return str
  if (target <= 0) return ''
  if (stringWidth(str) <= target) return str
 
  // We compute the number of bytes of ansi sequences here and add
  // that to our initial truncation to ensure that we don't slice one
  // that we want to keep in half.
  var noAnsi = stripAnsi(str)
  var ansiSize = str.length + noAnsi.length
  var truncated = str.slice(0, target + ansiSize)
 
  // we have to shrink the result to account for our ansi sequence buffer
  // (if an ansi sequence was truncated) and double width characters.
  while (stringWidth(truncated) > target) {
    truncated = truncated.slice(0, -1)
  }
  return truncated
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/

Statements: 48.84% (21 / 43)      Branches: 25% (5 / 20)      Functions: 60% (3 / 5)      Lines: 48.84% (21 / 43)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/
File Statements Branches Functions Lines
index.js 48.84% (21 / 43) 25% (5 / 20) 60% (3 / 5) 48.84% (21 / 43)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/index.js

Statements: 48.84% (21 / 43)      Branches: 25% (5 / 20)      Functions: 60% (3 / 5)      Lines: 48.84% (21 / 43)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85    1 1   1               1 1 1             1 1 1         1 1 10   1 10   1         1 1 20   1         1             1                                                      
'use strict';
/* eslint-disable no-unused-vars */
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
 
function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}
 
	return Object(val);
}
 
function shouldUseNative() {
	try {
		Iif (!Object.assign) {
			return false;
		}
 
		// Detect buggy property enumeration order in older V8 versions.
 
		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line
		test1[5] = 'de';
		Iif (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}
 
		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		Iif (order2.join('') !== '0123456789') {
			return false;
		}
 
		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		Iif (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}
 
		return true;
	} catch (e) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}
 
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;
 
	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);
 
		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}
 
		if (Object.getOwnPropertySymbols) {
			symbols = Object.getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}
 
	return to;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/

Statements: 67.42% (60 / 89)      Branches: 38.24% (13 / 34)      Functions: 41.67% (5 / 12)      Lines: 67.42% (60 / 89)      Ignored: 6 statements, 1 branch     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/
File Statements Branches Functions Lines
index.js 65.48% (55 / 84) 36.67% (11 / 30) 41.67% (5 / 12) 65.48% (55 / 84)
signals.js 100% (5 / 5) 50% (2 / 4) 100% (0 / 0) 100% (5 / 5)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/index.js

Statements: 65.48% (55 / 84)      Branches: 36.67% (11 / 30)      Functions: 41.67% (5 / 12)      Lines: 65.48% (55 / 84)      Ignored: 6 statements, 1 branch     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159      1 1   1   1 1     1 1     1 1 1             1 1 1     1 1   1 1     1 1       1             1   1     1 1                               1                 1 1 18                   1   1         1       1   1   1 1     1           1   1 18 18 18           1 1     1 1       1   1     1 1 3 1 1   1     1     2        
// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
var assert = require('assert')
var signals = require('./signals.js')
 
var EE = require('events')
/* istanbul ignore if */
Iif (typeof EE !== 'function') {
  EE = EE.EventEmitter
}
 
var emitter
Iif (process.__signal_exit_emitter__) {
  emitter = process.__signal_exit_emitter__
} else {
  emitter = process.__signal_exit_emitter__ = new EE()
  emitter.count = 0
  emitter.emitted = {}
}
 
// Because this emitter is a global, we have to check to see if a
// previous version of this library failed to enable infinite listeners.
// I know what you're about to say.  But literally everything about
// signal-exit is a compromise with evil.  Get used to it.
Eif (!emitter.infinite) {
  emitter.setMaxListeners(Infinity)
  emitter.infinite = true
}
 
module.exports = function (cb, opts) {
  assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler')
 
  Eif (loaded === false) {
    load()
  }
 
  var ev = 'exit'
  Iif (opts && opts.alwaysLast) {
    ev = 'afterexit'
  }
 
  var remove = function () {
    emitter.removeListener(ev, cb)
    if (emitter.listeners('exit').length === 0 &&
        emitter.listeners('afterexit').length === 0) {
      unload()
    }
  }
  emitter.on(ev, cb)
 
  return remove
}
 
module.exports.unload = unload
function unload () {
  if (!loaded) {
    return
  }
  loaded = false
 
  signals.forEach(function (sig) {
    try {
      process.removeListener(sig, sigListeners[sig])
    } catch (er) {}
  })
  process.emit = originalProcessEmit
  process.reallyExit = originalProcessReallyExit
  emitter.count -= 1
}
 
function emit (event, code, signal) {
  if (emitter.emitted[event]) {
    return
  }
  emitter.emitted[event] = true
  emitter.emit(event, code, signal)
}
 
// { <signal>: <listener fn>, ... }
var sigListeners = {}
signals.forEach(function (sig) {
  sigListeners[sig] = function listener () {
    // If there are no other listeners, an exit is coming!
    // Simplest way: remove us and then re-send the signal.
    // We know that this will kill the process, so we can
    // safely emit now.
    var listeners = process.listeners(sig)
    if (listeners.length === emitter.count) {
      unload()
      emit('exit', null, sig)
      /* istanbul ignore next */
      emit('afterexit', null, sig)
      /* istanbul ignore next */
      process.kill(process.pid, sig)
    }
  }
})
 
module.exports.signals = function () {
  return signals
}
 
module.exports.load = load
 
var loaded = false
 
function load () {
  Iif (loaded) {
    return
  }
  loaded = true
 
  // This is the number of onSignalExit's that are in play.
  // It's important so that we can count the correct number of
  // listeners on signals, and don't wait for the other one to
  // handle it instead of us.
  emitter.count += 1
 
  signals = signals.filter(function (sig) {
    try {
      process.on(sig, sigListeners[sig])
      return true
    } catch (er) {
      return false
    }
  })
 
  process.emit = processEmit
  process.reallyExit = processReallyExit
}
 
var originalProcessReallyExit = process.reallyExit
function processReallyExit (code) {
  process.exitCode = code || 0
  emit('exit', process.exitCode, null)
  /* istanbul ignore next */
  emit('afterexit', process.exitCode, null)
  /* istanbul ignore next */
  originalProcessReallyExit.call(process, process.exitCode)
}
 
var originalProcessEmit = process.emit
function processEmit (ev, arg) {
  if (ev === 'exit') {
    Eif (arg !== undefined) {
      process.exitCode = arg
    }
    var ret = originalProcessEmit.apply(this, arguments)
    emit('exit', process.exitCode, null)
    /* istanbul ignore next */
    emit('afterexit', process.exitCode, null)
    return ret
  } else {
    return originalProcessEmit.apply(this, arguments)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/signals.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/signals.js

Statements: 100% (5 / 5)      Branches: 50% (2 / 4)      Functions: 100% (0 / 0)      Lines: 100% (5 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                                        1               1 1                             1 1                  
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems.  Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL.  It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
//
// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
// artificially, inherently leave the process in a
// state from which it is not safe to try and enter JS
// listeners.
module.exports = [
  'SIGABRT',
  'SIGALRM',
  'SIGHUP',
  'SIGINT',
  'SIGTERM'
]
 
Eif (process.platform !== 'win32') {
  module.exports.push(
    'SIGVTALRM',
    'SIGXCPU',
    'SIGXFSZ',
    'SIGUSR2',
    'SIGTRAP',
    'SIGSYS',
    'SIGQUIT',
    'SIGIOT'
    // should detect profiler and enable/disable accordingly.
    // see #21
    // 'SIGPROF'
  )
}
 
Eif (process.platform === 'linux') {
  module.exports.push(
    'SIGIO',
    'SIGPOLL',
    'SIGPWR',
    'SIGSTKFLT',
    'SIGUNUSED'
  )
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/

Statements: 22.22% (4 / 18)      Branches: 0% (0 / 13)      Functions: 0% (0 / 1)      Lines: 22.22% (4 / 18)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/
File Statements Branches Functions Lines
index.js 22.22% (4 / 18) 0% (0 / 13) 0% (0 / 1) 22.22% (4 / 18)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/index.js

Statements: 22.22% (4 / 18)      Branches: 0% (0 / 13)      Functions: 0% (0 / 1)      Lines: 22.22% (4 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39  1 1 1     1                                                                
'use strict';
var stripAnsi = require('strip-ansi');
var codePointAt = require('code-point-at');
var isFullwidthCodePoint = require('is-fullwidth-code-point');
 
// https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1345
module.exports = function (str) {
	if (typeof str !== 'string' || str.length === 0) {
		return 0;
	}
 
	var width = 0;
 
	str = stripAnsi(str);
 
	for (var i = 0; i < str.length; i++) {
		var code = codePointAt(str, i);
 
		// ignore control characters
		if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
			continue;
		}
 
		// surrogates
		if (code >= 0x10000) {
			i++;
		}
 
		if (isFullwidthCodePoint(code)) {
			width += 2;
		} else {
			width++;
		}
	}
 
	return width;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/

Statements: 6.25% (1 / 16)      Branches: 0% (0 / 21)      Functions: 0% (0 / 1)      Lines: 6.25% (1 / 16)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/
File Statements Branches Functions Lines
index.js 6.25% (1 / 16) 0% (0 / 21) 0% (0 / 1) 6.25% (1 / 16)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/index.js

Statements: 6.25% (1 / 16)      Branches: 0% (0 / 21)      Functions: 0% (0 / 1)      Lines: 6.25% (1 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34    1                                                              
/* eslint-disable babel/new-cap, xo/throw-new-error */
'use strict';
module.exports = function (str, pos) {
	if (str === null || str === undefined) {
		throw TypeError();
	}
 
	str = String(str);
 
	var size = str.length;
	var i = pos ? Number(pos) : 0;
 
	if (Number.isNaN(i)) {
		i = 0;
	}
 
	if (i < 0 || i >= size) {
		return undefined;
	}
 
	var first = str.charCodeAt(i);
 
	if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) {
		var second = str.charCodeAt(i + 1);
 
		if (second >= 0xDC00 && second <= 0xDFFF) {
			return ((first - 0xD800) * 0x400) + second - 0xDC00 + 0x10000;
		}
	}
 
	return first;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 35)      Functions: 0% (0 / 1)      Lines: 28.57% (2 / 7)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/
File Statements Branches Functions Lines
index.js 28.57% (2 / 7) 0% (0 / 35) 0% (0 / 1) 28.57% (2 / 7)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/index.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 35)      Functions: 0% (0 / 1)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48  1   1                                                                                        
'use strict';
var numberIsNan = require('number-is-nan');
 
module.exports = function (x) {
	if (numberIsNan(x)) {
		return false;
	}
 
	// https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1369
 
	// code points are derived from:
	// http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
	if (x >= 0x1100 && (
		x <= 0x115f ||  // Hangul Jamo
		0x2329 === x || // LEFT-POINTING ANGLE BRACKET
		0x232a === x || // RIGHT-POINTING ANGLE BRACKET
		// CJK Radicals Supplement .. Enclosed CJK Letters and Months
		(0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
		// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
		0x3250 <= x && x <= 0x4dbf ||
		// CJK Unified Ideographs .. Yi Radicals
		0x4e00 <= x && x <= 0xa4c6 ||
		// Hangul Jamo Extended-A
		0xa960 <= x && x <= 0xa97c ||
		// Hangul Syllables
		0xac00 <= x && x <= 0xd7a3 ||
		// CJK Compatibility Ideographs
		0xf900 <= x && x <= 0xfaff ||
		// Vertical Forms
		0xfe10 <= x && x <= 0xfe19 ||
		// CJK Compatibility Forms .. Small Form Variants
		0xfe30 <= x && x <= 0xfe6b ||
		// Halfwidth and Fullwidth Forms
		0xff01 <= x && x <= 0xff60 ||
		0xffe0 <= x && x <= 0xffe6 ||
		// Kana Supplement
		0x1b000 <= x && x <= 0x1b001 ||
		// Enclosed Ideographic Supplement
		0x1f200 <= x && x <= 0x1f251 ||
		// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
		0x20000 <= x && x <= 0x3fffd)) {
		return true;
	}
 
	return false;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/
File Statements Branches Functions Lines
index.js 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/index.js

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

1 2 3 4 5 6  1        
'use strict';
module.exports = Number.isNaN || function (x) {
	return x !== x;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/

Statements: 18.18% (8 / 44)      Branches: 0% (0 / 20)      Functions: 0% (0 / 4)      Lines: 19.51% (8 / 41)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/
File Statements Branches Functions Lines
align.js 18.18% (8 / 44) 0% (0 / 20) 0% (0 / 4) 19.51% (8 / 41)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/align.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/align.js

Statements: 18.18% (8 / 44)      Branches: 0% (0 / 20)      Functions: 0% (0 / 4)      Lines: 19.51% (8 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67  1   1 1 1       1                             1                         1                         1                                
'use strict'
var stringWidth = require('string-width')
 
exports.center = alignCenter
exports.left = alignLeft
exports.right = alignRight
 
// lodash's way of generating pad characters.
 
function createPadding (width) {
  var result = ''
  var string = ' '
  var n = width
  do {
    if (n % 2) {
      result += string;
    }
    n = Math.floor(n / 2);
    string += string;
  } while (n);
 
  return result;
}
 
function alignLeft (str, width) {
  var trimmed = str.trimRight()
  if (trimmed.length === 0 && str.length >= width) return str
  var padding = ''
  var strWidth = stringWidth(trimmed)
 
  if (strWidth < width) {
    padding = createPadding(width - strWidth)
  }
 
  return trimmed + padding
}
 
function alignRight (str, width) {
  var trimmed = str.trimLeft()
  if (trimmed.length === 0 && str.length >= width) return str
  var padding = ''
  var strWidth = stringWidth(trimmed)
 
  if (strWidth < width) {
    padding = createPadding(width - strWidth)
  }
 
  return padding + trimmed
}
 
function alignCenter (str, width) {
  var trimmed = str.trim()
  if (trimmed.length === 0 && str.length >= width) return str
  var padLeft = ''
  var padRight = ''
  var strWidth = stringWidth(trimmed)
 
  if (strWidth < width) {
    var padLeftBy = parseInt((width - strWidth) / 2, 10)
    padLeft = createPadding(padLeftBy)
    padRight = createPadding(width - (strWidth + padLeftBy))
  }
 
  return padLeft + trimmed + padRight
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/set-blocking/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/set-blocking/

Statements: 100% (4 / 4)      Branches: 80% (4 / 5)      Functions: 100% (2 / 2)      Lines: 100% (4 / 4)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/set-blocking/
File Statements Branches Functions Lines
index.js 100% (4 / 4) 80% (4 / 5) 100% (2 / 2) 100% (4 / 4)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/set-blocking/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/npmlog/node_modules/set-blocking/index.js

Statements: 100% (4 / 4)      Branches: 80% (4 / 5)      Functions: 100% (2 / 2)      Lines: 100% (4 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 91 1 2 2          
module.exports = function (blocking) {
  [process.stdout, process.stderr].forEach(function (stream) {
    Eif (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') {
      stream._handle.setBlocking(blocking)
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/once/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/once/

Statements: 34.62% (9 / 26)      Branches: 0% (0 / 6)      Functions: 14.29% (1 / 7)      Lines: 36% (9 / 25)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/once/
File Statements Branches Functions Lines
once.js 34.62% (9 / 26) 0% (0 / 6) 14.29% (1 / 7) 36% (9 / 25)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/once/once.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/once/once.js

Statements: 34.62% (9 / 26)      Branches: 0% (0 / 6)      Functions: 14.29% (1 / 7)      Lines: 36% (9 / 25)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 441 1 1   1                               1 1         1 1     1                          
var wrappy = require('wrappy')
module.exports = wrappy(once)
module.exports.strict = wrappy(onceStrict)
 
once.proto = once(function () {
  Object.defineProperty(Function.prototype, 'once', {
    value: function () {
      return once(this)
    },
    configurable: true
  })
 
  Object.defineProperty(Function.prototype, 'onceStrict', {
    value: function () {
      return onceStrict(this)
    },
    configurable: true
  })
})
 
function once (fn) {
  var f = function () {
    if (f.called) return f.value
    f.called = true
    return f.value = fn.apply(this, arguments)
  }
  f.called = false
  return f
}
 
function onceStrict (fn) {
  var f = function () {
    if (f.called)
      throw new Error(f.onceError)
    f.called = true
    return f.value = fn.apply(this, arguments)
  }
  var name = fn.name || 'Function wrapped with `once`'
  f.onceError = name + " shouldn't be called more than once"
  f.called = false
  return f
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/opener/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/opener/

Statements: 18.18% (4 / 22)      Branches: 13.04% (3 / 23)      Functions: 0% (0 / 3)      Lines: 18.18% (4 / 22)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/opener/
File Statements Branches Functions Lines
opener.js 18.18% (4 / 22) 13.04% (3 / 23) 0% (0 / 3) 18.18% (4 / 22)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/opener/opener.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/opener/opener.js

Statements: 18.18% (4 / 22)      Branches: 13.04% (3 / 23)      Functions: 0% (0 / 3)      Lines: 18.18% (4 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62        1   1                                                                                       1     1                
//#!/usr/bin/env node
 
"use strict";
 
var childProcess = require("child_process");
 
function opener(args, options, callback) {
    // http://stackoverflow.com/q/1480971/3191, but see below for Windows.
    var command = process.platform === "win32" ? "cmd" :
                  process.platform === "darwin" ? "open" :
                  "xdg-open";
 
    if (typeof args === "string") {
        args = [args];
    }
 
    if (typeof options === "function") {
        callback = options;
        options = {};
    }
 
    if (options && typeof options === "object" && options.command) {
        if (process.platform === "win32") {
            // *always* use cmd on windows
            args = [options.command].concat(args);
        } else {
            command = options.command;
        }
    }
 
    if (process.platform === "win32") {
        // On Windows, we really want to use the "start" command. But, the rules regarding arguments with spaces, and
        // escaping them with quotes, can get really arcane. So the easiest way to deal with this is to pass off the
        // responsibility to "cmd /c", which has that logic built in.
        //
        // Furthermore, if "cmd /c" double-quoted the first parameter, then "start" will interpret it as a window title,
        // so we need to add a dummy empty-string window title: http://stackoverflow.com/a/154090/3191
        //
        // Additionally, on Windows ampersand needs to be escaped when passed to "start"
        args = args.map(function(value) {
            return value.replace(/&/g, '^&');
        });
        args = ["/c", "start", '""'].concat(args);
    }
 
    return childProcess.execFile(command, args, options, callback);
}
 
// Export `opener` for programmatic access.
// You might use this to e.g. open a website: `opener("http://google.com")`
module.exports = opener;
 
// If we're being called from the command line, just execute, using the command-line arguments.
Iif (require.main && require.main.id === module.id) {
    opener(process.argv.slice(2), function (error) {
        if (error) {
            throw error;
        }
    });
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/

Statements: 63.41% (26 / 41)      Branches: 27.78% (10 / 36)      Functions: 50% (6 / 12)      Lines: 68.42% (26 / 38)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/osenv/
File Statements Branches Functions Lines
osenv.js 63.41% (26 / 41) 27.78% (10 / 36) 50% (6 / 12) 68.42% (26 / 38)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/osenv.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/osenv.js

Statements: 63.41% (26 / 41)      Branches: 27.78% (10 / 36)      Functions: 50% (6 / 12)      Lines: 68.42% (26 / 38)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 741 1 1 1 1           1 8 8 8 4 4                 4       4 4       1             1       1       1 1     1 1     1           1 1         1 1        
var isWindows = process.platform === 'win32'
var path = require('path')
var exec = require('child_process').exec
var osTmpdir = require('os-tmpdir')
var osHomedir = require('os-homedir')
 
// looking up envs is a bit costly.
// Also, sometimes we want to have a fallback
// Pass in a callback to wait for the fallback on failures
// After the first lookup, always returns the same thing.
function memo (key, lookup, fallback) {
  var fell = false
  var falling = false
  exports[key] = function (cb) {
    var val = lookup()
    Iif (!val && !fell && !falling && fallback) {
      fell = true
      falling = true
      exec(fallback, function (er, output, stderr) {
        falling = false
        if (er) return // oh well, we tried
        val = output.trim()
      })
    }
    exports[key] = function (cb) {
      if (cb) process.nextTick(cb.bind(null, null, val))
      return val
    }
    Iif (cb && !falling) process.nextTick(cb.bind(null, null, val))
    return val
  }
}
 
memo('user', function () {
  return ( isWindows
         ? process.env.USERDOMAIN + '\\' + process.env.USERNAME
         : process.env.USER
         )
}, 'whoami')
 
memo('prompt', function () {
  return isWindows ? process.env.PROMPT : process.env.PS1
})
 
memo('hostname', function () {
  return isWindows ? process.env.COMPUTERNAME : process.env.HOSTNAME
}, 'hostname')
 
memo('tmpdir', function () {
  return osTmpdir()
})
 
memo('home', function () {
  return osHomedir()
})
 
memo('path', function () {
  return (process.env.PATH ||
          process.env.Path ||
          process.env.path).split(isWindows ? ';' : ':')
})
 
memo('editor', function () {
  return process.env.EDITOR ||
         process.env.VISUAL ||
         (isWindows ? 'notepad.exe' : 'vi')
})
 
memo('shell', function () {
  return isWindows ? process.env.ComSpec || 'cmd'
         : process.env.SHELL || 'bash'
})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-homedir/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-homedir/

Statements: 23.08% (3 / 13)      Branches: 3.57% (1 / 28)      Functions: 0% (0 / 1)      Lines: 23.08% (3 / 13)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-homedir/
File Statements Branches Functions Lines
index.js 23.08% (3 / 13) 3.57% (1 / 28) 0% (0 / 1) 23.08% (3 / 13)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-homedir/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-homedir/index.js

Statements: 23.08% (3 / 13)      Branches: 3.57% (1 / 28)      Functions: 0% (0 / 1)      Lines: 23.08% (3 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  1   1                                       1    
'use strict';
var os = require('os');
 
function homedir() {
	var env = process.env;
	var home = env.HOME;
	var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
 
	if (process.platform === 'win32') {
		return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null;
	}
 
	if (process.platform === 'darwin') {
		return home || (user ? '/Users/' + user : null);
	}
 
	if (process.platform === 'linux') {
		return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null));
	}
 
	return home || null;
}
 
module.exports = typeof os.homedir === 'function' ? os.homedir : homedir;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-tmpdir/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-tmpdir/

Statements: 80% (8 / 10)      Branches: 46.67% (7 / 15)      Functions: 100% (1 / 1)      Lines: 80% (8 / 10)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-tmpdir/
File Statements Branches Functions Lines
index.js 80% (8 / 10) 46.67% (7 / 15) 100% (1 / 1) 80% (8 / 10)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-tmpdir/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/osenv/node_modules/os-tmpdir/index.js

Statements: 80% (8 / 10)      Branches: 46.67% (7 / 15)      Functions: 100% (1 / 1)      Lines: 80% (8 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1 1     1 1   1         1           1       1      
'use strict';
var isWindows = process.platform === 'win32';
var trailingSlashRe = isWindows ? /[^:]\\$/ : /.\/$/;
 
// https://github.com/nodejs/node/blob/3e7a14381497a3b73dda68d05b5130563cdab420/lib/os.js#L25-L43
module.exports = function () {
	var path;
 
	Iif (isWindows) {
		path = process.env.TEMP ||
			process.env.TMP ||
			(process.env.SystemRoot || process.env.windir) + '\\temp';
	} else {
		path = process.env.TMPDIR ||
			process.env.TMP ||
			process.env.TEMP ||
			'/tmp';
	}
 
	Iif (trailingSlashRe.test(path)) {
		path = path.slice(0, -1);
	}
 
	return path;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/path-is-inside/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/path-is-inside/lib/

Statements: 25% (3 / 12)      Branches: 0% (0 / 7)      Functions: 0% (0 / 2)      Lines: 25% (3 / 12)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/path-is-inside/lib/
File Statements Branches Functions Lines
path-is-inside.js 25% (3 / 12) 0% (0 / 7) 0% (0 / 2) 25% (3 / 12)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/path-is-inside/lib/path-is-inside.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/path-is-inside/lib/path-is-inside.js

Statements: 25% (3 / 12)      Branches: 0% (0 / 7)      Functions: 0% (0 / 2)      Lines: 25% (3 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30    1   1                                   1              
"use strict";
 
var path = require("path");
 
module.exports = function (thePath, potentialParent) {
    // For inside-directory checking, we want to allow trailing slashes, so normalize.
    thePath = stripTrailingSep(thePath);
    potentialParent = stripTrailingSep(potentialParent);
 
    // Node treats only Windows as case-insensitive in its path module; we follow those conventions.
    if (process.platform === "win32") {
        thePath = thePath.toLowerCase();
        potentialParent = potentialParent.toLowerCase();
    }
 
    return thePath.lastIndexOf(potentialParent, 0) === 0 &&
		(
			thePath[potentialParent.length] === path.sep ||
			thePath[potentialParent.length] === undefined
		);
};
 
function stripTrailingSep(thePath) {
    if (thePath[thePath.length - 1] === path.sep) {
        return thePath.slice(0, -1);
    }
    return thePath;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-cmd-shim/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-cmd-shim/

Statements: 21.05% (8 / 38)      Branches: 0% (0 / 14)      Functions: 0% (0 / 8)      Lines: 22.86% (8 / 35)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read-cmd-shim/
File Statements Branches Functions Lines
index.js 21.05% (8 / 38) 0% (0 / 14) 0% (0 / 8) 22.86% (8 / 35)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-cmd-shim/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-cmd-shim/index.js

Statements: 21.05% (8 / 38)      Branches: 0% (0 / 14)      Functions: 0% (0 / 8)      Lines: 22.86% (8 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56  1   1               1         1         1           1                   1                     1              
'use strict'
var fs = require('graceful-fs')
 
function extractPath (path, cmdshimContents) {
  if (/[.]cmd$/.test(path)) {
    return extractPathFromCmd(cmdshimContents)
  } else {
    return extractPathFromCygwin(cmdshimContents)
  }
}
 
function extractPathFromCmd (cmdshimContents) {
  var matches = cmdshimContents.match(/"%~dp0\\([^"]+?)"\s+%[*]/)
  return matches && matches[1]
}
 
function extractPathFromCygwin (cmdshimContents) {
  var matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+"[$]@"/)
  return matches && matches[1]
}
 
function wrapError (thrown, newError) {
  newError.message = thrown.message
  newError.code = thrown.code
  return newError
}
 
function notaShim (path, er) {
  if (!er) {
    er = new Error()
    Error.captureStackTrace(er, notaShim)
  }
  er.code = 'ENOTASHIM'
  er.message = "Can't read shim path from '" + path + "', it doesn't appear to be a cmd-shim"
  return er
}
 
var readCmdShim = module.exports = function (path, cb) {
  var er = new Error()
  Error.captureStackTrace(er, readCmdShim)
  fs.readFile(path, function (readFileEr, contents) {
    if (readFileEr) return cb(wrapError(readFileEr, er))
    var destination = extractPath(path, contents.toString())
    if (destination) return cb(null, destination)
    return cb(notaShim(path, er))
  })
}
 
module.exports.sync = function (path) {
  var contents = fs.readFileSync(path)
  var destination = extractPath(path, contents.toString())
  if (!destination) throw notaShim(path)
  return destination
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/

Statements: 11.52% (22 / 191)      Branches: 0% (0 / 143)      Functions: 0% (0 / 28)      Lines: 12.79% (22 / 172)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read-installed/
File Statements Branches Functions Lines
read-installed.js 11.52% (22 / 191) 0% (0 / 143) 0% (0 / 28) 12.79% (22 / 172)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/read-installed.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/read-installed.js

Statements: 11.52% (22 / 191)      Branches: 0% (0 / 143)      Functions: 0% (0 / 28)      Lines: 12.79% (22 / 172)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409                                                                                                                                                                                  1 1         1 1 1 1 1 1 1   1   1       1   1   1                                                               1                                                                             1                                                                                                                                                                       1 1                                           1                                                                                                                       1                                                               1                               1                  
 
// Walk through the file-system "database" of installed
// packages, and create a data object related to the
// installed versions of each package.
 
/*
This will traverse through all node_modules folders,
resolving the dependencies object to the object corresponding to
the package that meets that dep, or just the version/range if
unmet.
 
Assuming that you had this folder structure:
 
/path/to
+-- package.json { name = "root" }
`-- node_modules
    +-- foo {bar, baz, asdf}
    | +-- node_modules
    |   +-- bar { baz }
    |   `-- baz
    `-- asdf
 
where "foo" depends on bar, baz, and asdf, bar depends on baz,
and bar and baz are bundled with foo, whereas "asdf" is at
the higher level (sibling to foo), you'd get this object structure:
 
{ <package.json data>
, path: "/path/to"
, parent: null
, dependencies:
  { foo :
    { version: "1.2.3"
    , path: "/path/to/node_modules/foo"
    , parent: <Circular: root>
    , dependencies:
      { bar:
        { parent: <Circular: foo>
        , path: "/path/to/node_modules/foo/node_modules/bar"
        , version: "2.3.4"
        , dependencies: { baz: <Circular: foo.dependencies.baz> }
        }
      , baz: { ... }
      , asdf: <Circular: asdf>
      }
    }
  , asdf: { ... }
  }
}
 
Unmet deps are left as strings.
Extraneous deps are marked with extraneous:true
deps that don't meet a requirement are marked with invalid:true
deps that don't meet a peer requirement are marked with peerInvalid:true
 
to READ(packagefolder, parentobj, name, reqver)
obj = read package.json
installed = ./node_modules/*
if parentobj is null, and no package.json
  obj = {dependencies:{<installed>:ANY}}
deps = Object.keys(obj.dependencies)
obj.path = packagefolder
obj.parent = parentobj
if name, && obj.name !== name, obj.invalid = true
if reqver, && obj.version !satisfies reqver, obj.invalid = true
if !reqver && parentobj, obj.extraneous = true
for each folder in installed
  obj.dependencies[folder] = READ(packagefolder+node_modules+folder,
                                  obj, folder, obj.dependencies[folder])
# walk tree to find unmet deps
for each dep in obj.dependencies not in installed
  r = obj.parent
  while r
    if r.dependencies[dep]
      if r.dependencies[dep].verion !satisfies obj.dependencies[dep]
        WARN
        r.dependencies[dep].invalid = true
      obj.dependencies[dep] = r.dependencies[dep]
      r = null
    else r = r.parent
return obj
 
 
TODO:
1. Find unmet deps in parent directories, searching as node does up
as far as the left-most node_modules folder.
2. Ignore anything in node_modules that isn't a package folder.
 
*/
 
try {
  var fs = require("graceful-fs")
} catch (er) {
  var fs = require("fs")
}
 
var path = require("path")
var asyncMap = require("slide").asyncMap
var semver = require("semver")
var readJson = require("read-package-json")
var url = require("url")
var util = require("util")
var extend = require("util-extend")
 
var debug = require("debuglog")("read-installed")
 
var readdir = require("readdir-scoped-modules")
 
// Sentinel catch-all version constraint used when a dependency is not
// listed in the package.json file.
var ANY = {}
 
module.exports = readInstalled
 
function readInstalled (folder, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  } else {
    opts = extend({}, opts)
  }
 
  if (typeof opts.depth !== 'number')
    opts.depth = Infinity
 
  opts.depth = Math.max(0, opts.depth)
 
  if (typeof opts.log !== 'function')
    opts.log = function () {}
 
  opts.dev = !!opts.dev
  opts.realpathSeen = {}
  opts.findUnmetSeen = []
 
 
  readInstalled_(folder, null, null, null, 0, opts, function (er, obj) {
    if (er) return cb(er)
    // now obj has all the installed things, where they're installed
    // figure out the inheritance links, now that the object is built.
    resolveInheritance(obj, opts)
    obj.root = true
    unmarkExtraneous(obj, opts)
    cb(null, obj)
  })
}
 
function readInstalled_ (folder, parent, name, reqver, depth, opts, cb) {
  var installed
    , obj
    , real
    , link
    , realpathSeen = opts.realpathSeen
 
  readdir(path.resolve(folder, "node_modules"), function (er, i) {
    // error indicates that nothing is installed here
    if (er) i = []
    installed = i.filter(function (f) { return f.charAt(0) !== "." })
    next()
  })
 
  readJson(path.resolve(folder, "package.json"), function (er, data) {
    obj = copy(data)
 
    if (!parent) {
      obj = obj || true
      er = null
    }
    return next(er)
  })
 
  fs.lstat(folder, function (er, st) {
    if (er) {
      if (!parent) real = true
      return next(er)
    }
    fs.realpath(folder, function (er, rp) {
      debug("realpath(%j) = %j", folder, rp)
      real = rp
      if (st.isSymbolicLink()) link = rp
      next(er)
    })
  })
 
  var errState = null
    , called = false
  function next (er) {
    if (errState) return
    if (er) {
      errState = er
      return cb(null, [])
    }
    debug('next', installed, obj && typeof obj, name, real)
    if (!installed || !obj || !real || called) return
    called = true
    if (realpathSeen[real]) return cb(null, realpathSeen[real])
    if (obj === true) {
      obj = {dependencies:{}, path:folder}
      installed.forEach(function (i) { obj.dependencies[i] = ANY })
    }
    if (name && obj.name !== name) obj.invalid = true
    obj.realName = name || obj.name
    obj.dependencies = obj.dependencies || {}
 
    // At this point, figure out what dependencies we NEED to get met
    obj._dependencies = copy(obj.dependencies)
 
    if (reqver === ANY) {
      // We were unable to determine the required version of this
      // dependency from the package.json file, but we now know its actual
      // version, so treat that version as the required version to avoid
      // marking the dependency as invalid below. See #40.
      reqver = obj.version;
    }
 
    // "foo":"http://blah" and "foo":"latest" are always presumed valid
    if (reqver
        && semver.validRange(reqver, true)
        && !semver.satisfies(obj.version, reqver, true)) {
      obj.invalid = true
    }
 
    // Mark as extraneous at this point.
    // This will be un-marked in unmarkExtraneous, where we mark as
    // not-extraneous everything that is required in some way from
    // the root object.
    obj.extraneous = true
 
    obj.path = obj.path || folder
    obj.realPath = real
    obj.link = link
    if (parent && !obj.link) obj.parent = parent
    realpathSeen[real] = obj
    obj.depth = depth
    //if (depth >= opts.depth) return cb(null, obj)
    asyncMap(installed, function (pkg, cb) {
      var rv = obj.dependencies[pkg]
      if (!rv && obj.devDependencies && opts.dev)
        rv = obj.devDependencies[pkg]
 
      if (depth > opts.depth) {
        obj.dependencies = {}
        return cb(null, obj)
      }
 
      readInstalled_( path.resolve(folder, "node_modules/"+pkg)
                    , obj, pkg, obj.dependencies[pkg], depth + 1, opts
                    , cb )
 
    }, function (er, installedData) {
      if (er) return cb(er)
      installedData.forEach(function (dep) {
        obj.dependencies[dep.realName] = dep
      })
 
      // any strings here are unmet things.  however, if it's
      // optional, then that's fine, so just delete it.
      if (obj.optionalDependencies) {
        Object.keys(obj.optionalDependencies).forEach(function (dep) {
          if (typeof obj.dependencies[dep] === "string") {
            delete obj.dependencies[dep]
          }
        })
      }
      return cb(null, obj)
    })
  }
}
 
// starting from a root object, call findUnmet on each layer of children
var riSeen = []
function resolveInheritance (obj, opts) {
  if (typeof obj !== "object") return
  if (riSeen.indexOf(obj) !== -1) return
  riSeen.push(obj)
  if (typeof obj.dependencies !== "object") {
    obj.dependencies = {}
  }
  Object.keys(obj.dependencies).forEach(function (dep) {
    findUnmet(obj.dependencies[dep], opts)
  })
  Object.keys(obj.dependencies).forEach(function (dep) {
    if (typeof obj.dependencies[dep] === "object") {
      resolveInheritance(obj.dependencies[dep], opts)
    } else {
      debug("unmet dep! %s %s@%s", obj.name, dep, obj.dependencies[dep])
    }
  })
  findUnmet(obj, opts)
}
 
// find unmet deps by walking up the tree object.
// No I/O
function findUnmet (obj, opts) {
  var findUnmetSeen = opts.findUnmetSeen
  if (findUnmetSeen.indexOf(obj) !== -1) return
  findUnmetSeen.push(obj)
  debug("find unmet parent=%s obj=", obj.parent && obj.parent.name, obj.name || obj)
  var deps = obj.dependencies = obj.dependencies || {}
 
  debug(deps)
  Object.keys(deps)
    .filter(function (d) { return typeof deps[d] === "string" })
    .forEach(function (d) {
      var found = findDep(obj, d)
      debug("finding dep %j", d, found && found.name || found)
      // "foo":"http://blah" and "foo":"latest" are always presumed valid
      if (typeof deps[d] === "string" &&
          semver.validRange(deps[d], true) &&
          found &&
          !semver.satisfies(found.version, deps[d], true)) {
        // the bad thing will happen
        opts.log( "unmet dependency"
                , obj.path + " requires "+d+"@'"+deps[d]
                + "' but will load\n"
                + found.path+",\nwhich is version "+found.version )
        found.invalid = true
      }
      if (found) {
        deps[d] = found
      }
    })
 
  var peerDeps = obj.peerDependencies = obj.peerDependencies || {}
  Object.keys(peerDeps).forEach(function (d) {
    var dependency
 
    if (!obj.parent) {
      dependency = obj.dependencies[d]
 
      // read it as a missing dep
      if (!dependency) {
        obj.dependencies[d] = peerDeps[d]
      }
    } else {
      var r = obj.parent
      while (r && !dependency) {
        dependency = r.dependencies && r.dependencies[d]
        r = r.link ? null : r.parent
      }
    }
 
    if (!dependency) {
      // mark as a missing dep!
      obj.dependencies[d] = peerDeps[d]
    } else if (!semver.satisfies(dependency.version, peerDeps[d], true)) {
      dependency.peerInvalid = true
    }
  })
 
  return obj
}
 
function unmarkExtraneous (obj, opts) {
  // Mark all non-required deps as extraneous.
  // start from the root object and mark as non-extraneous all modules
  // that haven't been previously flagged as extraneous then propagate
  // to all their dependencies
 
  obj.extraneous = false
 
  var deps = obj._dependencies || []
  if (opts.dev && obj.devDependencies && (obj.root || obj.link)) {
    Object.keys(obj.devDependencies).forEach(function (k) {
      deps[k] = obj.devDependencies[k]
    })
  }
 
  if (obj.peerDependencies) {
    Object.keys(obj.peerDependencies).forEach(function (k) {
      deps[k] = obj.peerDependencies[k]
    })
  }
 
  debug("not extraneous", obj._id, deps)
  Object.keys(deps).forEach(function (d) {
    var dep = findDep(obj, d)
    if (dep && dep.extraneous) {
      unmarkExtraneous(dep, opts)
    }
  })
}
 
// Find the one that will actually be loaded by require()
// so we can make sure it's valid etc.
function findDep (obj, d) {
  var r = obj
    , found = null
  while (r && !found) {
    // if r is a valid choice, then use that.
    // kinda weird if a pkg depends on itself, but after the first
    // iteration of this loop, it indicates a dep cycle.
    if (typeof r.dependencies[d] === "object") {
      found = r.dependencies[d]
    }
    if (!found && r.realName === d) found = r
    r = r.link ? null : r.parent
  }
  return found
}
 
function copy (obj) {
  if (!obj || typeof obj !== 'object') return obj
  if (Array.isArray(obj)) return obj.map(copy)
 
  var o = {}
  for (var i in obj) o[i] = copy(obj[i])
  return o
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/node_modules/util-extend/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/node_modules/util-extend/

Statements: 22.22% (2 / 9)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 25% (2 / 8)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read-installed/node_modules/util-extend/
File Statements Branches Functions Lines
extend.js 22.22% (2 / 9) 0% (0 / 4) 0% (0 / 1) 25% (2 / 8)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/node_modules/util-extend/extend.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-installed/node_modules/util-extend/extend.js

Statements: 22.22% (2 / 9)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 25% (2 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                          1 1                        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
module.exports = extend;
function extend(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || typeof add !== 'object') return origin;
 
  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/

Statements: 15.3% (43 / 281)      Branches: 0% (0 / 140)      Functions: 0% (0 / 54)      Lines: 17.92% (43 / 240)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read-package-json/
File Statements Branches Functions Lines
read-json.js 15.3% (43 / 281) 0% (0 / 140) 0% (0 / 54) 17.92% (43 / 240)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/read-json.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/read-json.js

Statements: 15.3% (43 / 281)      Branches: 0% (0 / 140)      Functions: 0% (0 / 54)      Lines: 17.92% (43 / 240)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 3961 1 1         1   1 1 1   1     1                     1   1                               1           1               1                                                 1                           1 1                                       1               1             1                     1                     1                 1                   1               1                   1                   1                                 1                             1                     1                   1               1                         1                       1                   1                                     1             1                           1     1                                 1           1         1                                   1              
var fs
try {
  fs = require('graceful-fs')
} catch (er) {
  fs = require('fs')
}
 
var path = require('path')
 
var glob = require('glob')
var normalizeData = require('normalize-package-data')
var safeJSON = require('json-parse-helpfulerror')
 
module.exports = readJson
 
// put more stuff on here to customize.
readJson.extraSet = [
  gypfile,
  serverjs,
  scriptpath,
  authors,
  readme,
  mans,
  bins,
  githead
]
 
var typoWarned = {}
 
function readJson (file, log_, strict_, cb_) {
  var log, strict, cb
  for (var i = 1; i < arguments.length - 1; i++) {
    if (typeof arguments[i] === 'boolean') {
      strict = arguments[i]
    } else if (typeof arguments[i] === 'function') {
      log = arguments[i]
    }
  }
 
  if (!log) log = function () {}
  cb = arguments[ arguments.length - 1 ]
 
  readJson_(file, log, strict, cb)
}
 
function readJson_ (file, log, strict, cb) {
  fs.readFile(file, 'utf8', function (er, d) {
    parseJson(file, er, d, log, strict, cb)
  })
}
 
function stripBOM (content) {
  // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  // because the buffer-to-string conversion in `fs.readFileSync()`
  // translates it to FEFF, the UTF-16 BOM.
  if (content.charCodeAt(0) === 0xFEFF) content = content.slice(1)
  return content
}
 
function parseJson (file, er, d, log, strict, cb) {
  if (er && er.code === 'ENOENT') {
    return fs.stat(path.dirname(file), function (err, stat) {
      if (!err && stat && !stat.isDirectory()) {
        // ENOTDIR isn't used on Windows, but npm expects it.
        er = Object.create(er)
        er.code = 'ENOTDIR'
        return cb(er)
      } else {
        return indexjs(file, er, log, strict, cb)
      }
    })
  }
  if (er) return cb(er)
 
  try {
    d = safeJSON.parse(stripBOM(d))
  } catch (er) {
    d = parseIndex(d)
    if (!d) return cb(parseError(er, file))
  }
 
  extras(file, d, log, strict, cb)
}
 
function indexjs (file, er, log, strict, cb) {
  if (path.basename(file) === 'index.js') return cb(er)
 
  var index = path.resolve(path.dirname(file), 'index.js')
  fs.readFile(index, 'utf8', function (er2, d) {
    if (er2) return cb(er)
 
    d = parseIndex(d)
    if (!d) return cb(er)
 
    extras(file, d, log, strict, cb)
  })
}
 
readJson.extras = extras
function extras (file, data, log_, strict_, cb_) {
  var log, strict, cb
  for (var i = 2; i < arguments.length - 1; i++) {
    if (typeof arguments[i] === 'boolean') {
      strict = arguments[i]
    } else if (typeof arguments[i] === 'function') {
      log = arguments[i]
    }
  }
 
  if (!log) log = function () {}
  cb = arguments[i]
 
  var set = readJson.extraSet
  var n = set.length
  var errState = null
  set.forEach(function (fn) {
    fn(file, data, then)
  })
 
  function then (er) {
    if (errState) return
    if (er) return cb(errState = er)
    if (--n > 0) return
    final(file, data, log, strict, cb)
  }
}
 
function scriptpath (file, data, cb) {
  if (!data.scripts) return cb(null, data)
  var k = Object.keys(data.scripts)
  k.forEach(scriptpath_, data.scripts)
  cb(null, data)
}
 
function scriptpath_ (key) {
  var s = this[key]
  // This is never allowed, and only causes problems
  if (typeof s !== 'string') return delete this[key]
 
  var spre = /^(\.[/\\])?node_modules[/\\].bin[\\/]/
  if (s.match(spre)) {
    this[key] = this[key].replace(spre, '')
  }
}
 
function gypfile (file, data, cb) {
  var dir = path.dirname(file)
  var s = data.scripts || {}
  if (s.install || s.preinstall) return cb(null, data)
 
  glob('*.gyp', { cwd: dir }, function (er, files) {
    if (er) return cb(er)
    gypfile_(file, data, files, cb)
  })
}
 
function gypfile_ (file, data, files, cb) {
  if (!files.length) return cb(null, data)
  var s = data.scripts || {}
  s.install = 'node-gyp rebuild'
  data.scripts = s
  data.gypfile = true
  return cb(null, data)
}
 
function serverjs (file, data, cb) {
  var dir = path.dirname(file)
  var s = data.scripts || {}
  if (s.start) return cb(null, data)
  glob('server.js', { cwd: dir }, function (er, files) {
    if (er) return cb(er)
    serverjs_(file, data, files, cb)
  })
}
 
function serverjs_ (file, data, files, cb) {
  if (!files.length) return cb(null, data)
  var s = data.scripts || {}
  s.start = 'node server.js'
  data.scripts = s
  return cb(null, data)
}
 
function authors (file, data, cb) {
  if (data.contributors) return cb(null, data)
  var af = path.resolve(path.dirname(file), 'AUTHORS')
  fs.readFile(af, 'utf8', function (er, ad) {
    // ignore error.  just checking it.
    if (er) return cb(null, data)
    authors_(file, data, ad, cb)
  })
}
 
function authors_ (file, data, ad, cb) {
  ad = ad.split(/\r?\n/g).map(function (line) {
    return line.replace(/^\s*#.*$/, '').trim()
  }).filter(function (line) {
    return line
  })
  data.contributors = ad
  return cb(null, data)
}
 
function readme (file, data, cb) {
  if (data.readme) return cb(null, data)
  var dir = path.dirname(file)
  var globOpts = { cwd: dir, nocase: true, mark: true }
  glob('{README,README.*}', globOpts, function (er, files) {
    if (er) return cb(er)
    // don't accept directories.
    files = files.filter(function (file) {
      return !file.match(/\/$/)
    })
    if (!files.length) return cb()
    var fn = preferMarkdownReadme(files)
    var rm = path.resolve(dir, fn)
    readme_(file, data, rm, cb)
  })
}
 
function preferMarkdownReadme (files) {
  var fallback = 0
  var re = /\.m?a?r?k?d?o?w?n?$/i
  for (var i = 0; i < files.length; i++) {
    if (files[i].match(re)) {
      return files[i]
    } else if (files[i].match(/README$/)) {
      fallback = i
    }
  }
  // prefer README.md, followed by README; otherwise, return
  // the first filename (which could be README)
  return files[fallback]
}
 
function readme_ (file, data, rm, cb) {
  var rmfn = path.basename(rm)
  fs.readFile(rm, 'utf8', function (er, rm) {
    // maybe not readable, or something.
    if (er) return cb()
    data.readme = rm
    data.readmeFilename = rmfn
    return cb(er, data)
  })
}
 
function mans (file, data, cb) {
  var m = data.directories && data.directories.man
  if (data.man || !m) return cb(null, data)
  m = path.resolve(path.dirname(file), m)
  glob('**/*.[0-9]', { cwd: m }, function (er, mans) {
    if (er) return cb(er)
    mans_(file, data, mans, cb)
  })
}
 
function mans_ (file, data, mans, cb) {
  var m = data.directories && data.directories.man
  data.man = mans.map(function (mf) {
    return path.resolve(path.dirname(file), m, mf)
  })
  return cb(null, data)
}
 
function bins (file, data, cb) {
  if (Array.isArray(data.bin)) return bins_(file, data, data.bin, cb)
 
  var m = data.directories && data.directories.bin
  if (data.bin || !m) return cb(null, data)
 
  m = path.resolve(path.dirname(file), m)
  glob('**', { cwd: m }, function (er, bins) {
    if (er) return cb(er)
    bins_(file, data, bins, cb)
  })
}
 
function bins_ (file, data, bins, cb) {
  var m = (data.directories && data.directories.bin) || '.'
  data.bin = bins.reduce(function (acc, mf) {
    if (mf && mf.charAt(0) !== '.') {
      var f = path.basename(mf)
      acc[f] = path.join(m, mf)
    }
    return acc
  }, {})
  return cb(null, data)
}
 
function githead (file, data, cb) {
  if (data.gitHead) return cb(null, data)
  var dir = path.dirname(file)
  var head = path.resolve(dir, '.git/HEAD')
  fs.readFile(head, 'utf8', function (er, head) {
    if (er) return cb(null, data)
    githead_(file, data, dir, head, cb)
  })
}
 
function githead_ (file, data, dir, head, cb) {
  if (!head.match(/^ref: /)) {
    data.gitHead = head.trim()
    return cb(null, data)
  }
  var headFile = head.replace(/^ref: /, '').trim()
  headFile = path.resolve(dir, '.git', headFile)
  fs.readFile(headFile, 'utf8', function (er, head) {
    if (er || !head) return cb(null, data)
    head = head.replace(/^ref: /, '').trim()
    data.gitHead = head
    return cb(null, data)
  })
}
 
/**
 * Warn if the bin references don't point to anything.  This might be better in
 * normalize-package-data if it had access to the file path.
 */
function checkBinReferences_ (file, data, warn, cb) {
  if (!(data.bin instanceof Object)) return cb()
 
  var keys = Object.keys(data.bin)
  var keysLeft = keys.length
  if (!keysLeft) return cb()
 
  function handleExists (relName, result) {
    keysLeft--
    if (!result) warn('No bin file found at ' + relName)
    if (!keysLeft) cb()
  }
 
  keys.forEach(function (key) {
    var dirName = path.dirname(file)
    var relName = data.bin[key]
    var binPath = path.resolve(dirName, relName)
    fs.exists(binPath, handleExists.bind(null, relName))
  })
}
 
function final (file, data, log, strict, cb) {
  var pId = makePackageId(data)
 
  function warn (msg) {
    if (typoWarned[pId]) return
    if (log) log('package.json', pId, msg)
  }
 
  try {
    normalizeData(data, warn, strict)
  } catch (error) {
    return cb(error)
  }
 
  checkBinReferences_(file, data, warn, function () {
    typoWarned[pId] = true
    cb(null, data)
  })
}
 
function makePackageId (data) {
  var name = cleanString(data.name)
  var ver = cleanString(data.version)
  return name + '@' + ver
}
 
function cleanString (str) {
  return (!str || typeof (str) !== 'string') ? '' : str.trim()
}
 
// /**package { "name": "foo", "version": "1.2.3", ... } **/
function parseIndex (data) {
  data = data.split(/^\/\*\*package(?:\s|$)/m)
 
  if (data.length < 2) return null
  data = data[1]
  data = data.split(/\*\*\/$/m)
 
  if (data.length < 2) return null
  data = data[0]
  data = data.replace(/^\s*\*/mg, '')
 
  try {
    return safeJSON.parse(data)
  } catch (er) {
    return null
  }
}
 
function parseError (ex, file) {
  var e = new Error('Failed to parse json\n' + ex.message)
  e.code = 'EJSONPARSE'
  e.file = file
  return e
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/

Statements: 42.86% (3 / 7)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 42.86% (3 / 7)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/
File Statements Branches Functions Lines
index.js 42.86% (3 / 7) 100% (0 / 0) 0% (0 / 1) 42.86% (3 / 7)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/index.js

Statements: 42.86% (3 / 7)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 42.86% (3 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23    1   1                               1    
'use strict';
 
var jju = require('jju');
 
function parse(text, reviver) {
    try {
        return JSON.parse(text, reviver);
    } catch (err) {
        // we expect this to throw with a more informative message
        jju.parse(text, {
            mode: 'json',
            reviver: reviver
        });
 
        // backup if jju is not as strict as JSON.parse; re-throw error
        // data-dependent code path, I do not know how to cover it
        throw err;
    }
}
 
exports.parse = parse;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/node_modules/jju/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/node_modules/jju/

Statements: 50% (6 / 12)      Branches: 100% (0 / 0)      Functions: 0% (0 / 6)      Lines: 50% (6 / 12)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/node_modules/jju/
File Statements Branches Functions Lines
index.js 50% (6 / 12) 100% (0 / 0) 0% (0 / 6) 50% (6 / 12)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/node_modules/jju/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/node_modules/jju/index.js

Statements: 50% (6 / 12)      Branches: 100% (0 / 0)      Functions: 0% (0 / 6)      Lines: 50% (6 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  1       1       1       1       1       1                        
 
module.exports.__defineGetter__('parse', function() {
	return require('./lib/parse').parse
})
 
module.exports.__defineGetter__('stringify', function() {
	return require('./lib/stringify').stringify
})
 
module.exports.__defineGetter__('tokenize', function() {
	return require('./lib/parse').tokenize
})
 
module.exports.__defineGetter__('update', function() {
	return require('./lib/document').update
})
 
module.exports.__defineGetter__('analyze', function() {
	return require('./lib/analyze').analyze
})
 
module.exports.__defineGetter__('utils', function() {
	return require('./lib/utils')
})
 
/**package
{ "name": "jju",
  "version": "0.0.0",
  "dependencies": {"js-yaml": "*"},
  "scripts": {"postinstall": "js-yaml package.yaml > package.json ; npm install"}
}
**/
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-tree/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-tree/

Statements: 25.31% (41 / 162)      Branches: 0% (0 / 63)      Functions: 0% (0 / 27)      Lines: 27.15% (41 / 151)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read-package-tree/
File Statements Branches Functions Lines
rpt.js 25.31% (41 / 162) 0% (0 / 63) 0% (0 / 27) 27.15% (41 / 151)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-tree/rpt.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read-package-tree/rpt.js

Statements: 25.31% (41 / 162)      Branches: 0% (0 / 63)      Functions: 0% (0 / 27)      Lines: 27.15% (41 / 151)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 2371 1 1 1 1 1 1   1             1                   1               1   1 1   1 1                                         1 1 1 1 1   1                                           1     1 1   1         1                   1                         1                     1           1                   1         1               1           1               1                               1                 1         1                   1         1                   1          
var fs = require('fs')
var rpj = require('read-package-json')
var path = require('path')
var dz = require('dezalgo')
var once = require('once')
var readdir = require('readdir-scoped-modules')
var debug = require('debuglog')('rpt')
 
function asyncForEach (items, todo, done) {
  var remaining = items.length
  if (remaining === 0) return done()
  var seenErr
  items.forEach(function (item) {
    todo(item, handleComplete)
  })
  function handleComplete (err) {
    if (seenErr) return
    if (err) {
      seenErr = true
      return done(err)
    }
    if (--remaining === 0) done()
  }
}
 
function dpath (p) {
  if (!p) return ''
  if (p.indexOf(process.cwd()) === 0) {
    p = p.substr(process.cwd().length + 1)
  }
  return p
}
 
module.exports = rpt
 
rpt.Node = Node
rpt.Link = Link
 
var ID = 0
function Node (pkg, logical, physical, er, cache) {
  if (cache[physical]) return cache[physical]
 
  if (!(this instanceof Node)) {
    return new Node(pkg, logical, physical, er, cache)
  }
 
  cache[physical] = this
 
  debug(this.constructor.name, dpath(physical), pkg && pkg._id)
 
  this.id = ID++
  this.package = pkg || {}
  this.path = logical
  this.realpath = physical
  this.parent = null
  this.isLink = false
  this.children = []
  this.error = er
}
 
Node.prototype.package = null
Node.prototype.path = ''
Node.prototype.realpath = ''
Node.prototype.children = null
Node.prototype.error = null
 
function Link (pkg, logical, physical, realpath, er, cache) {
  if (cache[physical]) return cache[physical]
 
  if (!(this instanceof Link)) {
    return new Link(pkg, logical, physical, realpath, er, cache)
  }
 
  cache[physical] = this
 
  debug(this.constructor.name, dpath(physical), pkg && pkg._id)
 
  this.id = ID++
  this.path = logical
  this.realpath = realpath
  this.package = pkg || {}
  this.parent = null
  this.target = new Node(this.package, logical, realpath, er, cache)
  this.isLink = true
  this.children = this.target.children
  this.error = er
}
 
Link.prototype = Object.create(Node.prototype, {
  constructor: { value: Link }
})
Link.prototype.target = null
Link.prototype.realpath = ''
 
function loadNode (logical, physical, cache, cb) {
  debug('loadNode', dpath(logical))
  return fs.realpath(physical, thenReadPackageJson)
 
  var realpath
  function thenReadPackageJson (er, real) {
    if (er) {
      var node = new Node(null, logical, physical, er, cache)
      return cb(null, node)
    }
    debug('realpath l=%j p=%j real=%j', dpath(logical), dpath(physical), dpath(real))
    var pj = path.join(real, 'package.json')
    realpath = real
    return rpj(pj, thenCreateNode)
  }
  function thenCreateNode (er, pkg) {
    pkg = pkg || null
    var node
    if (physical === realpath) {
      node = new Node(pkg, logical, physical, er, cache)
    } else {
      node = new Link(pkg, logical, physical, realpath, er, cache)
    }
 
    cb(null, node)
  }
}
 
function loadChildren (node, cache, filterWith, cb) {
  debug('loadChildren', dpath(node.path))
  // needed 'cause we process all kids async-like and errors
  // short circuit, so we have to be sure that after an error
  // the cbs from other kids don't result in calling cb a second
  // (or more) time.
  cb = once(cb)
  var nm = path.join(node.path, 'node_modules')
  var rm
  return fs.realpath(path.join(node.path, 'node_modules'), thenReaddir)
 
  function thenReaddir (er, real_nm) {
    if (er) return cb(null, node)
    rm = real_nm
    readdir(nm, thenLoadKids)
  }
 
  function thenLoadKids (er, kids) {
    // If there are no children, that's fine, just return
    if (er) return cb(null, node)
 
    kids = kids.filter(function (kid) {
      return kid[0] !== '.' && (!filterWith || filterWith(node, kid))
    })
 
    asyncForEach(kids, thenLoadNode, thenSortChildren)
  }
  function thenLoadNode (kid, done) {
    var kidPath = path.join(nm, kid)
    var kidRealPath = path.join(rm, kid)
    loadNode(kidPath, kidRealPath, cache, andAddNode(done))
  }
  function andAddNode (done) {
    return function (er, kid) {
      if (er) return done(er)
      node.children.push(kid)
      kid.parent = node
      done()
    }
  }
  function thenSortChildren (er) {
    sortChildren(node)
    cb(er, node)
  }
}
 
function sortChildren (node) {
  node.children = node.children.sort(function (a, b) {
    a = a.package.name ? a.package.name.toLowerCase() : a.path
    b = b.package.name ? b.package.name.toLowerCase() : b.path
    return a > b ? 1 : -1
  })
}
 
function loadTree (node, did, cache, filterWith, cb) {
  debug('loadTree', dpath(node.path), !!cache[node.path])
 
  if (did[node.realpath]) {
    return dz(cb)(null, node)
  }
 
  did[node.realpath] = true
 
  // needed 'cause we process all kids async-like and errors
  // short circuit, so we have to be sure that after an error
  // the cbs from other kids don't result in calling cb a second
  // (or more) time.
  cb = once(cb)
  return loadChildren(node, cache, filterWith, thenProcessChildren)
 
  function thenProcessChildren (er, node) {
    if (er) return cb(er)
 
    var kids = node.children.filter(function (kid) {
      return !did[kid.realpath]
    })
 
    return asyncForEach(kids, loadTreeForKid, cb)
  }
  function loadTreeForKid (kid, done) {
    loadTree(kid, did, cache, filterWith, done)
  }
}
 
function rpt (root, filterWith, cb) {
  if (!cb) {
    cb = filterWith
    filterWith = null
  }
  var cache = Object.create(null)
  var topErr
  var tree
  return fs.realpath(root, thenLoadNode)
 
  function thenLoadNode (er, realRoot) {
    if (er) return cb(er)
    debug('rpt', dpath(realRoot))
    loadNode(root, realRoot, cache, thenLoadTree)
  }
  function thenLoadTree(er, node) {
    // even if there's an error, it's fine, as long as we got a node
    if (node) {
      topErr = er
      tree = node
      loadTree(node, {}, cache, filterWith, thenHandleErrors)
    } else {
      cb(er)
    }
  }
  function thenHandleErrors (er) {
    cb(topErr && topErr.code !== 'ENOENT' ? topErr : er, tree)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/lib/

Statements: 9.21% (7 / 76)      Branches: 0% (0 / 47)      Functions: 0% (0 / 6)      Lines: 9.46% (7 / 74)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read/lib/
File Statements Branches Functions Lines
read.js 9.21% (7 / 76) 0% (0 / 47) 0% (0 / 6) 9.46% (7 / 74)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/lib/read.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/lib/read.js

Statements: 9.21% (7 / 76)      Branches: 0% (0 / 47)      Functions: 0% (0 / 6)      Lines: 9.46% (7 / 74)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115  1   1 1   1                                                                                                                                         1                             1           1                                    
 
module.exports = read
 
var readline = require('readline')
var Mute = require('mute-stream')
 
function read (opts, cb) {
  if (opts.num) {
    throw new Error('read() no longer accepts a char number limit')
  }
 
  if (typeof opts.default !== 'undefined' &&
      typeof opts.default !== 'string' &&
      typeof opts.default !== 'number') {
    throw new Error('default value must be string or number')
  }
 
  var input = opts.input || process.stdin
  var output = opts.output || process.stdout
  var prompt = (opts.prompt || '').trim() + ' '
  var silent = opts.silent
  var editDef = false
  var timeout = opts.timeout
 
  var def = opts.default || ''
  if (def) {
    if (silent) {
      prompt += '(<default hidden>) '
    } else if (opts.edit) {
      editDef = true
    } else {
      prompt += '(' + def + ') '
    }
  }
  var terminal = !!(opts.terminal || output.isTTY)
 
  var m = new Mute({ replace: opts.replace, prompt: prompt })
  m.pipe(output, {end: false})
  output = m
  var rlOpts = { input: input, output: output, terminal: terminal }
 
  if (process.version.match(/^v0\.6/)) {
    var rl = readline.createInterface(rlOpts.input, rlOpts.output)
  } else {
    var rl = readline.createInterface(rlOpts)
  }
 
 
  output.unmute()
  rl.setPrompt(prompt)
  rl.prompt()
  if (silent) {
    output.mute()
  } else if (editDef) {
    rl.line = def
    rl.cursor = def.length
    rl._refreshLine()
  }
 
  var called = false
  rl.on('line', onLine)
  rl.on('error', onError)
 
  rl.on('SIGINT', function () {
    rl.close()
    onError(new Error('canceled'))
  })
 
  var timer
  if (timeout) {
    timer = setTimeout(function () {
      onError(new Error('timed out'))
    }, timeout)
  }
 
  function done () {
    called = true
    rl.close()
 
    if (process.version.match(/^v0\.6/)) {
      rl.input.removeAllListeners('data')
      rl.input.removeAllListeners('keypress')
      rl.input.pause()
    }
 
    clearTimeout(timer)
    output.mute()
    output.end()
  }
 
  function onError (er) {
    if (called) return
    done()
    return cb(er)
  }
 
  function onLine (line) {
    if (called) return
    if (silent && terminal) {
      output.unmute()
      output.write('\r\n')
    }
    done()
    // truncate the \n at the end.
    line = line.replace(/\r?\n$/, '')
    var isDefault = !!(editDef && line === def)
    if (def && !line) {
      isDefault = true
      line = def
    }
    cb(null, line, isDefault)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/node_modules/mute-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/node_modules/mute-stream/

Statements: 34.29% (24 / 70)      Branches: 0% (0 / 47)      Functions: 6.67% (1 / 15)      Lines: 36.51% (23 / 63)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/read/node_modules/mute-stream/
File Statements Branches Functions Lines
mute.js 34.29% (24 / 70) 0% (0 / 47) 6.67% (1 / 15) 36.51% (23 / 63)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/node_modules/mute-stream/mute.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/read/node_modules/mute-stream/mute.js

Statements: 34.29% (24 / 70)      Branches: 0% (0 / 47)      Functions: 6.67% (1 / 15)      Lines: 36.51% (23 / 63)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 1421   1       1                             1   1         1       1       1             1       1             1               1                 1             1               1         1       1       1                                     1                       3             1 1 1    
var Stream = require('stream')
 
module.exports = MuteStream
 
// var out = new MuteStream(process.stdout)
// argument auto-pipes
function MuteStream (opts) {
  Stream.apply(this)
  opts = opts || {}
  this.writable = this.readable = true
  this.muted = false
  this.on('pipe', this._onpipe)
  this.replace = opts.replace
 
  // For readline-type situations
  // This much at the start of a line being redrawn after a ctrl char
  // is seen (such as backspace) won't be redrawn as the replacement
  this._prompt = opts.prompt || null
  this._hadControl = false
}
 
MuteStream.prototype = Object.create(Stream.prototype)
 
Object.defineProperty(MuteStream.prototype, 'constructor', {
  value: MuteStream,
  enumerable: false
})
 
MuteStream.prototype.mute = function () {
  this.muted = true
}
 
MuteStream.prototype.unmute = function () {
  this.muted = false
}
 
Object.defineProperty(MuteStream.prototype, '_onpipe', {
  value: onPipe,
  enumerable: false,
  writable: true,
  configurable: true
})
 
function onPipe (src) {
  this._src = src
}
 
Object.defineProperty(MuteStream.prototype, 'isTTY', {
  get: getIsTTY,
  set: setIsTTY,
  enumerable: true,
  configurable: true
})
 
function getIsTTY () {
  return( (this._dest) ? this._dest.isTTY
        : (this._src) ? this._src.isTTY
        : false
        )
}
 
// basically just get replace the getter/setter with a regular value
function setIsTTY (isTTY) {
  Object.defineProperty(this, 'isTTY', {
    value: isTTY,
    enumerable: true,
    writable: true,
    configurable: true
  })
}
 
Object.defineProperty(MuteStream.prototype, 'rows', {
  get: function () {
    return( this._dest ? this._dest.rows
          : this._src ? this._src.rows
          : undefined )
  }, enumerable: true, configurable: true })
 
Object.defineProperty(MuteStream.prototype, 'columns', {
  get: function () {
    return( this._dest ? this._dest.columns
          : this._src ? this._src.columns
          : undefined )
  }, enumerable: true, configurable: true })
 
 
MuteStream.prototype.pipe = function (dest) {
  this._dest = dest
  return Stream.prototype.pipe.call(this, dest)
}
 
MuteStream.prototype.pause = function () {
  if (this._src) return this._src.pause()
}
 
MuteStream.prototype.resume = function () {
  if (this._src) return this._src.resume()
}
 
MuteStream.prototype.write = function (c) {
  if (this.muted) {
    if (!this.replace) return true
    if (c.match(/^\u001b/)) {
      this._hadControl = true
      return this.emit('data', c)
    } else {
      if (this._prompt && this._hadControl &&
          c.indexOf(this._prompt) === 0) {
        this._hadControl = false
        this.emit('data', this._prompt)
        c = c.substr(this._prompt.length)
      }
      c = c.toString().replace(/./g, this.replace)
    }
  }
  this.emit('data', c)
}
 
MuteStream.prototype.end = function (c) {
  if (this.muted) {
    if (c && this.replace) {
      c = c.toString().replace(/./g, this.replace)
    } else {
      c = null
    }
  }
  if (c) this.emit('data', c)
  this.emit('end')
}
 
function proxy (fn) { return function () {
  var d = this._dest
  var s = this._src
  if (d && d[fn]) d[fn].apply(d, arguments)
  if (s && s[fn]) s[fn].apply(s, arguments)
}}
 
MuteStream.prototype.destroy = proxy('destroy')
MuteStream.prototype.destroySoon = proxy('destroySoon')
MuteStream.prototype.close = proxy('close')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/

Statements: 92.31% (12 / 13)      Branches: 57.14% (4 / 7)      Functions: 100% (1 / 1)      Lines: 92.31% (12 / 13)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/
File Statements Branches Functions Lines
readable.js 91.67% (11 / 12) 57.14% (4 / 7) 100% (1 / 1) 91.67% (11 / 12)
transform.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/readable.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/readable.js

Statements: 91.67% (11 / 12)      Branches: 57.14% (4 / 7)      Functions: 100% (1 / 1)      Lines: 91.67% (11 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 181 1 1     1 1 1 1 1 1 1   1        
var Stream = (function (){
  try {
    return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
  } catch(_){}
}());
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
 
Iif (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
  module.exports = Stream;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/transform.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/transform.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require("./lib/_stream_transform.js")
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/

Statements: 16.38% (161 / 983)      Branches: 2.59% (15 / 580)      Functions: 2.75% (3 / 109)      Lines: 18.39% (160 / 870)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/
File Statements Branches Functions Lines
_stream_duplex.js 43.59% (17 / 39) 13.64% (3 / 22) 0% (0 / 5) 48.48% (16 / 33)
_stream_passthrough.js 63.64% (7 / 11) 0% (0 / 2) 0% (0 / 2) 70% (7 / 10)
_stream_readable.js 12.97% (72 / 555) 1.14% (4 / 352) 1.79% (1 / 56) 14.78% (72 / 487)
_stream_transform.js 16.67% (13 / 78) 0% (0 / 42) 0% (0 / 11) 19.4% (13 / 67)
_stream_writable.js 17.33% (52 / 300) 4.94% (8 / 162) 5.71% (2 / 35) 19.05% (52 / 273)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_duplex.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_duplex.js

Statements: 43.59% (17 / 39)      Branches: 13.64% (3 / 22)      Functions: 0% (0 / 5)      Lines: 48.48% (16 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                  1               1     1       1 1     1 1   1   1 1 8 8     1                                 1                   1       1          
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
 
'use strict';
 
/*<replacement>*/
 
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    keys.push(key);
  }return keys;
};
/*</replacement>*/
 
module.exports = Duplex;
 
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
 
util.inherits(Duplex, Readable);
 
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
  var method = keys[v];
  if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
 
function Duplex(options) {
  if (!(this instanceof Duplex)) return new Duplex(options);
 
  Readable.call(this, options);
  Writable.call(this, options);
 
  if (options && options.readable === false) this.readable = false;
 
  if (options && options.writable === false) this.writable = false;
 
  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
 
  this.once('end', onend);
}
 
// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended) return;
 
  // no more data can be written.
  // But allow more writes to happen in this tick.
  processNextTick(onEndNT, this);
}
 
function onEndNT(self) {
  self.end();
}
 
function forEach(xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_passthrough.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_passthrough.js

Statements: 63.64% (7 / 11)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 70% (7 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27            1   1     1 1     1   1           1      
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
 
'use strict';
 
module.exports = PassThrough;
 
var Transform = require('./_stream_transform');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
util.inherits(PassThrough, Transform);
 
function PassThrough(options) {
  if (!(this instanceof PassThrough)) return new PassThrough(options);
 
  Transform.call(this, options);
}
 
PassThrough.prototype._transform = function (chunk, encoding, cb) {
  cb(null, chunk);
};
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_readable.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_readable.js

Statements: 12.97% (72 / 555)      Branches: 1.14% (4 / 352)      Functions: 1.79% (1 / 56)      Lines: 14.78% (72 / 487)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942    1     1       1       1     1     1   1           1 1 1 1   1         1   1       1 1       1 1 1 1           1 1   1   1                           1                                                                                                                                         1                                     1                             1         1       1                                                                                                             1         1               1 1                                     1                                     1                                                                                                                                                                                                       1               1                                   1                   1                       1             1                               1       1                                               1             1                         1                                                       1                                       1                     1         1             1                                 1                       1                                                                                                     1                                         1   1             1                   1             1                         1                   1                 1                                                                                                                         1           1                                       1                                       1                                                         1                                                     1                         1                 1           1            
'use strict';
 
module.exports = Readable;
 
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
 
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
 
/*<replacement>*/
var Duplex;
/*</replacement>*/
 
Readable.ReadableState = ReadableState;
 
/*<replacement>*/
var EE = require('events').EventEmitter;
 
var EElistenerCount = function (emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/
 
/*<replacement>*/
var Stream;
(function () {
  try {
    Stream = require('st' + 'ream');
  } catch (_) {} finally {
    Iif (!Stream) Stream = require('events').EventEmitter;
  }
})();
/*</replacement>*/
 
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
Eif (debugUtil && debugUtil.debuglog) {
  debug = debugUtil.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/
 
var BufferList = require('./internal/streams/BufferList');
var StringDecoder;
 
util.inherits(Readable, Stream);
 
function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
  // event emitter implementation with them.
  if (typeof emitter.prependListener === 'function') {
    return emitter.prependListener(event, fn);
  } else {
    // This is a hack to make sure that our error handler is attached before any
    // userland ones.  NEVER DO THIS. This is here only because this code needs
    // to continue to work with older versions of Node.js that do not include
    // the prependListener() method. The goal is to eventually remove this hack.
    if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  }
}
 
function ReadableState(options, stream) {
  Duplex = Duplex || require('./_stream_duplex');
 
  options = options || {};
 
  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;
 
  if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
 
  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  // A linked list is used to store data chunks instead of an array because the
  // linked list can remove elements from the beginning faster than
  // array.shift()
  this.buffer = new BufferList();
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
  this.resumeScheduled = false;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // when piping, we only care about 'readable' events that happen
  // after read()ing all the bytes and not getting any pushback.
  this.ranOut = false;
 
  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;
 
  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;
 
  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}
 
function Readable(options) {
  Duplex = Duplex || require('./_stream_duplex');
 
  if (!(this instanceof Readable)) return new Readable(options);
 
  this._readableState = new ReadableState(options, this);
 
  // legacy
  this.readable = true;
 
  if (options && typeof options.read === 'function') this._read = options.read;
 
  Stream.call(this);
}
 
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
  var state = this._readableState;
 
  if (!state.objectMode && typeof chunk === 'string') {
    encoding = encoding || state.defaultEncoding;
    if (encoding !== state.encoding) {
      chunk = bufferShim.from(chunk, encoding);
      encoding = '';
    }
  }
 
  return readableAddChunk(this, state, chunk, encoding, false);
};
 
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
  var state = this._readableState;
  return readableAddChunk(this, state, chunk, '', true);
};
 
Readable.prototype.isPaused = function () {
  return this._readableState.flowing === false;
};
 
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  var er = chunkInvalid(state, chunk);
  if (er) {
    stream.emit('error', er);
  } else if (chunk === null) {
    state.reading = false;
    onEofChunk(stream, state);
  } else if (state.objectMode || chunk && chunk.length > 0) {
    if (state.ended && !addToFront) {
      var e = new Error('stream.push() after EOF');
      stream.emit('error', e);
    } else if (state.endEmitted && addToFront) {
      var _e = new Error('stream.unshift() after end event');
      stream.emit('error', _e);
    } else {
      var skipAdd;
      if (state.decoder && !addToFront && !encoding) {
        chunk = state.decoder.write(chunk);
        skipAdd = !state.objectMode && chunk.length === 0;
      }
 
      if (!addToFront) state.reading = false;
 
      // Don't add to the buffer if we've decoded to an empty string chunk and
      // we're not in object mode
      if (!skipAdd) {
        // if we want the data now, just emit it.
        if (state.flowing && state.length === 0 && !state.sync) {
          stream.emit('data', chunk);
          stream.read(0);
        } else {
          // update the buffer info.
          state.length += state.objectMode ? 1 : chunk.length;
          if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
 
          if (state.needReadable) emitReadable(stream);
        }
      }
 
      maybeReadMore(stream, state);
    }
  } else if (!addToFront) {
    state.reading = false;
  }
 
  return needMoreData(state);
}
 
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
 
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
  if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
  return this;
};
 
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2 to prevent increasing hwm excessively in
    // tiny amounts
    n--;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n++;
  }
  return n;
}
 
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
  if (n <= 0 || state.length === 0 && state.ended) return 0;
  if (state.objectMode) return 1;
  if (n !== n) {
    // Only flow one buffer at a time
    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  }
  // If we're asking for more than the current hwm, then raise the hwm.
  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  if (n <= state.length) return n;
  // Don't have enough
  if (!state.ended) {
    state.needReadable = true;
    return 0;
  }
  return state.length;
}
 
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
  debug('read', n);
  n = parseInt(n, 10);
  var state = this._readableState;
  var nOrig = n;
 
  if (n !== 0) state.emittedReadable = false;
 
  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
    return null;
  }
 
  n = howMuchToRead(n, state);
 
  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0) endReadable(this);
    return null;
  }
 
  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.
 
  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);
 
  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }
 
  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  } else if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0) state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
    // If _read pushed data synchronously, then `reading` will be false,
    // and we need to re-evaluate how much data we can return to the user.
    if (!state.reading) n = howMuchToRead(nOrig, state);
  }
 
  var ret;
  if (n > 0) ret = fromList(n, state);else ret = null;
 
  if (ret === null) {
    state.needReadable = true;
    n = 0;
  } else {
    state.length -= n;
  }
 
  if (state.length === 0) {
    // If we have nothing in the buffer, then we want to know
    // as soon as we *do* get something into the buffer.
    if (!state.ended) state.needReadable = true;
 
    // If we tried to read() past the EOF, then emit end on the next tick.
    if (nOrig !== n && state.ended) endReadable(this);
  }
 
  if (ret !== null) this.emit('data', ret);
 
  return ret;
};
 
function chunkInvalid(state, chunk) {
  var er = null;
  if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}
 
function onEofChunk(stream, state) {
  if (state.ended) return;
  if (state.decoder) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;
 
  // emit 'readable' now to make sure it gets picked up.
  emitReadable(stream);
}
 
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  }
}
 
function emitReadable_(stream) {
  debug('emit readable');
  stream.emit('readable');
  flow(stream);
}
 
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    processNextTick(maybeReadMore_, stream, state);
  }
}
 
function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;else len = state.length;
  }
  state.readingMore = false;
}
 
// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
  this.emit('error', new Error('_read() is not implemented'));
};
 
Readable.prototype.pipe = function (dest, pipeOpts) {
  var src = this;
  var state = this._readableState;
 
  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
 
  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
 
  var endFn = doEnd ? onend : cleanup;
  if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
 
  dest.on('unpipe', onunpipe);
  function onunpipe(readable) {
    debug('onunpipe');
    if (readable === src) {
      cleanup();
    }
  }
 
  function onend() {
    debug('onend');
    dest.end();
  }
 
  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);
 
  var cleanedUp = false;
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', cleanup);
    src.removeListener('data', ondata);
 
    cleanedUp = true;
 
    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  }
 
  // If the user pushes more data while we're writing to dest then we'll end up
  // in ondata again. However, we only want to increase awaitDrain once because
  // dest will only emit one 'drain' event for the multiple writes.
  // => Introduce a guard on increasing awaitDrain.
  var increasedAwaitDrain = false;
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    increasedAwaitDrain = false;
    var ret = dest.write(chunk);
    if (false === ret && !increasedAwaitDrain) {
      // If the user unpiped during `dest.write()`, it is possible
      // to get stuck in a permanently paused state if that write
      // also returned false.
      // => Check whether `dest` is still a piping destination.
      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
        debug('false write response, pause', src._readableState.awaitDrain);
        src._readableState.awaitDrain++;
        increasedAwaitDrain = true;
      }
      src.pause();
    }
  }
 
  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  }
 
  // Make sure our error handler is attached before userland ones.
  prependListener(dest, 'error', onerror);
 
  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);
 
  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }
 
  // tell the dest that it's being piped to
  dest.emit('pipe', src);
 
  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }
 
  return dest;
};
 
function pipeOnDrain(src) {
  return function () {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain) state.awaitDrain--;
    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}
 
Readable.prototype.unpipe = function (dest) {
  var state = this._readableState;
 
  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0) return this;
 
  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes) return this;
 
    if (!dest) dest = state.pipes;
 
    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest) dest.emit('unpipe', this);
    return this;
  }
 
  // slow case. multiple pipe destinations.
 
  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
 
    for (var i = 0; i < len; i++) {
      dests[i].emit('unpipe', this);
    }return this;
  }
 
  // try to find the right one.
  var index = indexOf(state.pipes, dest);
  if (index === -1) return this;
 
  state.pipes.splice(index, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1) state.pipes = state.pipes[0];
 
  dest.emit('unpipe', this);
 
  return this;
};
 
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);
 
  if (ev === 'data') {
    // Start flowing on next tick if stream isn't explicitly paused
    if (this._readableState.flowing !== false) this.resume();
  } else if (ev === 'readable') {
    var state = this._readableState;
    if (!state.endEmitted && !state.readableListening) {
      state.readableListening = state.needReadable = true;
      state.emittedReadable = false;
      if (!state.reading) {
        processNextTick(nReadingNextTick, this);
      } else if (state.length) {
        emitReadable(this, state);
      }
    }
  }
 
  return res;
};
Readable.prototype.addListener = Readable.prototype.on;
 
function nReadingNextTick(self) {
  debug('readable nexttick read 0');
  self.read(0);
}
 
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    state.flowing = true;
    resume(this, state);
  }
  return this;
};
 
function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    processNextTick(resume_, stream, state);
  }
}
 
function resume_(stream, state) {
  if (!state.reading) {
    debug('resume read 0');
    stream.read(0);
  }
 
  state.resumeScheduled = false;
  state.awaitDrain = 0;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading) stream.read(0);
}
 
Readable.prototype.pause = function () {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (false !== this._readableState.flowing) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  return this;
};
 
function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  while (state.flowing && stream.read() !== null) {}
}
 
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
  var state = this._readableState;
  var paused = false;
 
  var self = this;
  stream.on('end', function () {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) self.push(chunk);
    }
 
    self.push(null);
  });
 
  stream.on('data', function (chunk) {
    debug('wrapped data');
    if (state.decoder) chunk = state.decoder.write(chunk);
 
    // don't skip over falsy values in objectMode
    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
 
    var ret = self.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });
 
  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (this[i] === undefined && typeof stream[i] === 'function') {
      this[i] = function (method) {
        return function () {
          return stream[method].apply(stream, arguments);
        };
      }(i);
    }
  }
 
  // proxy certain important events.
  var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  forEach(events, function (ev) {
    stream.on(ev, self.emit.bind(self, ev));
  });
 
  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  self._read = function (n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };
 
  return self;
};
 
// exposed for testing purposes only.
Readable._fromList = fromList;
 
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
  // nothing buffered
  if (state.length === 0) return null;
 
  var ret;
  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
    // read it all, truncate the list
    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
    state.buffer.clear();
  } else {
    // read part of list
    ret = fromListPartial(n, state.buffer, state.decoder);
  }
 
  return ret;
}
 
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
  var ret;
  if (n < list.head.data.length) {
    // slice is the same for buffers and strings
    ret = list.head.data.slice(0, n);
    list.head.data = list.head.data.slice(n);
  } else if (n === list.head.data.length) {
    // first chunk is a perfect match
    ret = list.shift();
  } else {
    // result spans more than one buffer
    ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  }
  return ret;
}
 
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
  var p = list.head;
  var c = 1;
  var ret = p.data;
  n -= ret.length;
  while (p = p.next) {
    var str = p.data;
    var nb = n > str.length ? str.length : n;
    if (nb === str.length) ret += str;else ret += str.slice(0, n);
    n -= nb;
    if (n === 0) {
      if (nb === str.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = str.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}
 
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
  var ret = bufferShim.allocUnsafe(n);
  var p = list.head;
  var c = 1;
  p.data.copy(ret);
  n -= p.data.length;
  while (p = p.next) {
    var buf = p.data;
    var nb = n > buf.length ? buf.length : n;
    buf.copy(ret, ret.length - n, 0, nb);
    n -= nb;
    if (n === 0) {
      if (nb === buf.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = buf.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}
 
function endReadable(stream) {
  var state = stream._readableState;
 
  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
 
  if (!state.endEmitted) {
    state.ended = true;
    processNextTick(endReadableNT, state, stream);
  }
}
 
function endReadableNT(state, stream) {
  // Check that we didn't get one last unshift.
  if (!state.endEmitted && state.length === 0) {
    state.endEmitted = true;
    stream.readable = false;
    stream.emit('end');
  }
}
 
function forEach(xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
function indexOf(xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_transform.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_transform.js

Statements: 16.67% (13 / 78)      Branches: 0% (0 / 42)      Functions: 0% (0 / 11)      Lines: 19.4% (13 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183                                                                                        1   1     1 1     1   1                       1                                           1                                                             1                             1       1                           1                         1                                
// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
 
'use strict';
 
module.exports = Transform;
 
var Duplex = require('./_stream_duplex');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
util.inherits(Transform, Duplex);
 
function TransformState(stream) {
  this.afterTransform = function (er, data) {
    return afterTransform(stream, er, data);
  };
 
  this.needTransform = false;
  this.transforming = false;
  this.writecb = null;
  this.writechunk = null;
  this.writeencoding = null;
}
 
function afterTransform(stream, er, data) {
  var ts = stream._transformState;
  ts.transforming = false;
 
  var cb = ts.writecb;
 
  if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
 
  ts.writechunk = null;
  ts.writecb = null;
 
  if (data !== null && data !== undefined) stream.push(data);
 
  cb(er);
 
  var rs = stream._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    stream._read(rs.highWaterMark);
  }
}
 
function Transform(options) {
  if (!(this instanceof Transform)) return new Transform(options);
 
  Duplex.call(this, options);
 
  this._transformState = new TransformState(this);
 
  var stream = this;
 
  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;
 
  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;
 
  if (options) {
    if (typeof options.transform === 'function') this._transform = options.transform;
 
    if (typeof options.flush === 'function') this._flush = options.flush;
  }
 
  // When the writable side finishes, then flush out anything remaining.
  this.once('prefinish', function () {
    if (typeof this._flush === 'function') this._flush(function (er, data) {
      done(stream, er, data);
    });else done(stream);
  });
}
 
Transform.prototype.push = function (chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};
 
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
  throw new Error('_transform() is not implemented');
};
 
Transform.prototype._write = function (chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  }
};
 
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
  var ts = this._transformState;
 
  if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};
 
function done(stream, er, data) {
  if (er) return stream.emit('error', er);
 
  if (data !== null && data !== undefined) stream.push(data);
 
  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  var ws = stream._writableState;
  var ts = stream._transformState;
 
  if (ws.length) throw new Error('Calling transform done when ws.length != 0');
 
  if (ts.transforming) throw new Error('Calling transform done when still transforming');
 
  return stream.push(null);
}
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_writable.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/_stream_writable.js

Statements: 17.33% (52 / 300)      Branches: 4.94% (8 / 162)      Functions: 5.71% (2 / 35)      Lines: 19.05% (52 / 273)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552            1     1       1       1     1     1 1       1           1 1 1 1   1         1   1     1   1   1             1                                                                                                                                                                                               1                   1 1 1                   1 1 1 1                         1                                                         1       1                   1                                 1                                           1           1                   1               1                   1                                                         1                 1               1             1                                                 1                   1               1                                                                                                                 1       1   1                                               1       1             1                           1                       1                                          
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
 
'use strict';
 
module.exports = Writable;
 
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
 
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/*</replacement>*/
 
/*<replacement>*/
var Duplex;
/*</replacement>*/
 
Writable.WritableState = WritableState;
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
/*<replacement>*/
var internalUtil = {
  deprecate: require('util-deprecate')
};
/*</replacement>*/
 
/*<replacement>*/
var Stream;
(function () {
  try {
    Stream = require('st' + 'ream');
  } catch (_) {} finally {
    Iif (!Stream) Stream = require('events').EventEmitter;
  }
})();
/*</replacement>*/
 
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
 
util.inherits(Writable, Stream);
 
function nop() {}
 
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
  this.next = null;
}
 
function WritableState(options, stream) {
  Duplex = Duplex || require('./_stream_duplex');
 
  options = options || {};
 
  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;
 
  if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
 
  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  // drain event flag.
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;
 
  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;
 
  // a flag to see when we're in the middle of a write.
  this.writing = false;
 
  // when true all writes will be buffered until .uncork() call
  this.corked = 0;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;
 
  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function (er) {
    onwrite(stream, er);
  };
 
  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;
 
  // the amount that is being written when _write is called.
  this.writelen = 0;
 
  this.bufferedRequest = null;
  this.lastBufferedRequest = null;
 
  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;
 
  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;
 
  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;
 
  // count buffered requests
  this.bufferedRequestCount = 0;
 
  // allocate the first CorkedRequest, there is always
  // one allocated and free to use, and we maintain at most two
  this.corkedRequestsFree = new CorkedRequest(this);
}
 
WritableState.prototype.getBuffer = function getBuffer() {
  var current = this.bufferedRequest;
  var out = [];
  while (current) {
    out.push(current);
    current = current.next;
  }
  return out;
};
 
(function () {
  try {
    Object.defineProperty(WritableState.prototype, 'buffer', {
      get: internalUtil.deprecate(function () {
        return this.getBuffer();
      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
    });
  } catch (_) {}
})();
 
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
Eif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  realHasInstance = Function.prototype[Symbol.hasInstance];
  Object.defineProperty(Writable, Symbol.hasInstance, {
    value: function (object) {
      if (realHasInstance.call(this, object)) return true;
 
      return object && object._writableState instanceof WritableState;
    }
  });
} else {
  realHasInstance = function (object) {
    return object instanceof this;
  };
}
 
function Writable(options) {
  Duplex = Duplex || require('./_stream_duplex');
 
  // Writable ctor is applied to Duplexes, too.
  // `realHasInstance` is necessary because using plain `instanceof`
  // would return false, as no `_writableState` property is attached.
 
  // Trying to use the custom `instanceof` for Writable here will also break the
  // Node.js LazyTransform implementation, which has a non-trivial getter for
  // `_writableState` that would lead to infinite recursion.
  if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
    return new Writable(options);
  }
 
  this._writableState = new WritableState(options, this);
 
  // legacy.
  this.writable = true;
 
  if (options) {
    if (typeof options.write === 'function') this._write = options.write;
 
    if (typeof options.writev === 'function') this._writev = options.writev;
  }
 
  Stream.call(this);
}
 
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
  this.emit('error', new Error('Cannot pipe, not readable'));
};
 
function writeAfterEnd(stream, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  processNextTick(cb, er);
}
 
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  var er = false;
 
  if (chunk === null) {
    er = new TypeError('May not write null values to stream');
  } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  if (er) {
    stream.emit('error', er);
    processNextTick(cb, er);
    valid = false;
  }
  return valid;
}
 
Writable.prototype.write = function (chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
  var isBuf = Buffer.isBuffer(chunk);
 
  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
 
  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
 
  if (typeof cb !== 'function') cb = nop;
 
  if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  }
 
  return ret;
};
 
Writable.prototype.cork = function () {
  var state = this._writableState;
 
  state.corked++;
};
 
Writable.prototype.uncork = function () {
  var state = this._writableState;
 
  if (state.corked) {
    state.corked--;
 
    if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  }
};
 
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  // node::ParseEncoding() requires lower case.
  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};
 
function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
    chunk = bufferShim.from(chunk, encoding);
  }
  return chunk;
}
 
// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    chunk = decodeChunk(state, chunk, encoding);
    if (Buffer.isBuffer(chunk)) encoding = 'buffer';
  }
  var len = state.objectMode ? 1 : chunk.length;
 
  state.length += len;
 
  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret) state.needDrain = true;
 
  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
    if (last) {
      last.next = state.lastBufferedRequest;
    } else {
      state.bufferedRequest = state.lastBufferedRequest;
    }
    state.bufferedRequestCount += 1;
  } else {
    doWrite(stream, state, false, len, chunk, encoding, cb);
  }
 
  return ret;
}
 
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}
 
function onwriteError(stream, state, sync, er, cb) {
  --state.pendingcb;
  if (sync) processNextTick(cb, er);else cb(er);
 
  stream._writableState.errorEmitted = true;
  stream.emit('error', er);
}
 
function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}
 
function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;
 
  onwriteStateUpdate(state);
 
  if (er) onwriteError(stream, state, sync, er, cb);else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(state);
 
    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
      clearBuffer(stream, state);
    }
 
    if (sync) {
      /*<replacement>*/
      asyncWrite(afterWrite, stream, state, finished, cb);
      /*</replacement>*/
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}
 
function afterWrite(stream, state, finished, cb) {
  if (!finished) onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}
 
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}
 
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
  var entry = state.bufferedRequest;
 
  if (stream._writev && entry && entry.next) {
    // Fast case, write everything using _writev()
    var l = state.bufferedRequestCount;
    var buffer = new Array(l);
    var holder = state.corkedRequestsFree;
    holder.entry = entry;
 
    var count = 0;
    while (entry) {
      buffer[count] = entry;
      entry = entry.next;
      count += 1;
    }
 
    doWrite(stream, state, true, state.length, buffer, '', holder.finish);
 
    // doWrite is almost always async, defer these to save a bit of time
    // as the hot path ends with doWrite
    state.pendingcb++;
    state.lastBufferedRequest = null;
    if (holder.next) {
      state.corkedRequestsFree = holder.next;
      holder.next = null;
    } else {
      state.corkedRequestsFree = new CorkedRequest(state);
    }
  } else {
    // Slow case, write chunks one-by-one
    while (entry) {
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;
 
      doWrite(stream, state, false, len, chunk, encoding, cb);
      entry = entry.next;
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        break;
      }
    }
 
    if (entry === null) state.lastBufferedRequest = null;
  }
 
  state.bufferedRequestCount = 0;
  state.bufferedRequest = entry;
  state.bufferProcessing = false;
}
 
Writable.prototype._write = function (chunk, encoding, cb) {
  cb(new Error('_write() is not implemented'));
};
 
Writable.prototype._writev = null;
 
Writable.prototype.end = function (chunk, encoding, cb) {
  var state = this._writableState;
 
  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
 
  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
 
  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }
 
  // ignore unnecessary end() calls.
  if (!state.ending && !state.finished) endWritable(this, state, cb);
};
 
function needFinish(state) {
  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
 
function prefinish(stream, state) {
  if (!state.prefinished) {
    state.prefinished = true;
    stream.emit('prefinish');
  }
}
 
function finishMaybe(stream, state) {
  var need = needFinish(state);
  if (need) {
    if (state.pendingcb === 0) {
      prefinish(stream, state);
      state.finished = true;
      stream.emit('finish');
    } else {
      prefinish(stream, state);
    }
  }
  return need;
}
 
function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished) processNextTick(cb);else stream.once('finish', cb);
  }
  state.ended = true;
  stream.writable = false;
}
 
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
  var _this = this;
 
  this.next = null;
  this.entry = null;
  this.finish = function (err) {
    var entry = _this.entry;
    _this.entry = null;
    while (entry) {
      var cb = entry.callback;
      state.pendingcb--;
      cb(err);
      entry = entry.next;
    }
    if (state.corkedRequestsFree) {
      state.corkedRequestsFree.next = _this;
    } else {
      state.corkedRequestsFree = _this;
    }
  };
}
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/internal/streams/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/internal/streams/

Statements: 18.87% (10 / 53)      Branches: 0% (0 / 14)      Functions: 0% (0 / 7)      Lines: 22.73% (10 / 44)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/internal/streams/
File Statements Branches Functions Lines
BufferList.js 18.87% (10 / 53) 0% (0 / 14) 0% (0 / 7) 22.73% (10 / 44)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/internal/streams/BufferList.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/lib/internal/streams/BufferList.js

Statements: 18.87% (10 / 53)      Branches: 0% (0 / 14)      Functions: 0% (0 / 7)      Lines: 22.73% (10 / 44)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65    1   1     1   1           1             1             1               1         1                 1                          
'use strict';
 
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
 
module.exports = BufferList;
 
function BufferList() {
  this.head = null;
  this.tail = null;
  this.length = 0;
}
 
BufferList.prototype.push = function (v) {
  var entry = { data: v, next: null };
  if (this.length > 0) this.tail.next = entry;else this.head = entry;
  this.tail = entry;
  ++this.length;
};
 
BufferList.prototype.unshift = function (v) {
  var entry = { data: v, next: this.head };
  if (this.length === 0) this.tail = entry;
  this.head = entry;
  ++this.length;
};
 
BufferList.prototype.shift = function () {
  if (this.length === 0) return;
  var ret = this.head.data;
  if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  --this.length;
  return ret;
};
 
BufferList.prototype.clear = function () {
  this.head = this.tail = null;
  this.length = 0;
};
 
BufferList.prototype.join = function (s) {
  if (this.length === 0) return '';
  var p = this.head;
  var ret = '' + p.data;
  while (p = p.next) {
    ret += s + p.data;
  }return ret;
};
 
BufferList.prototype.concat = function (n) {
  if (this.length === 0) return bufferShim.alloc(0);
  if (this.length === 1) return this.head.data;
  var ret = bufferShim.allocUnsafe(n >>> 0);
  var p = this.head;
  var i = 0;
  while (p) {
    p.data.copy(ret, i);
    i += p.data.length;
    p = p.next;
  }
  return ret;
};
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/buffer-shims/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/buffer-shims/

Statements: 10.81% (8 / 74)      Branches: 1.59% (1 / 63)      Functions: 0% (0 / 4)      Lines: 10.81% (8 / 74)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/buffer-shims/
File Statements Branches Functions Lines
index.js 10.81% (8 / 74) 1.59% (1 / 63) 0% (0 / 4) 10.81% (8 / 74)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/buffer-shims/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/buffer-shims/index.js

Statements: 10.81% (8 / 74)      Branches: 1.59% (1 / 63)      Functions: 0% (0 / 4)      Lines: 10.81% (8 / 74)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110    1 1 1 1 1                                                               1                       1                                                                                           1                          
'use strict';
 
var buffer = require('buffer');
var Buffer = buffer.Buffer;
var SlowBuffer = buffer.SlowBuffer;
var MAX_LEN = buffer.kMaxLength || 2147483647;
exports.alloc = function alloc(size, fill, encoding) {
  if (typeof Buffer.alloc === 'function') {
    return Buffer.alloc(size, fill, encoding);
  }
  if (typeof encoding === 'number') {
    throw new TypeError('encoding must not be number');
  }
  if (typeof size !== 'number') {
    throw new TypeError('size must be a number');
  }
  if (size > MAX_LEN) {
    throw new RangeError('size is too large');
  }
  var enc = encoding;
  var _fill = fill;
  if (_fill === undefined) {
    enc = undefined;
    _fill = 0;
  }
  var buf = new Buffer(size);
  if (typeof _fill === 'string') {
    var fillBuf = new Buffer(_fill, enc);
    var flen = fillBuf.length;
    var i = -1;
    while (++i < size) {
      buf[i] = fillBuf[i % flen];
    }
  } else {
    buf.fill(_fill);
  }
  return buf;
}
exports.allocUnsafe = function allocUnsafe(size) {
  if (typeof Buffer.allocUnsafe === 'function') {
    return Buffer.allocUnsafe(size);
  }
  if (typeof size !== 'number') {
    throw new TypeError('size must be a number');
  }
  if (size > MAX_LEN) {
    throw new RangeError('size is too large');
  }
  return new Buffer(size);
}
exports.from = function from(value, encodingOrOffset, length) {
  if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
    return Buffer.from(value, encodingOrOffset, length);
  }
  if (typeof value === 'number') {
    throw new TypeError('"value" argument must not be a number');
  }
  if (typeof value === 'string') {
    return new Buffer(value, encodingOrOffset);
  }
  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
    var offset = encodingOrOffset;
    if (arguments.length === 1) {
      return new Buffer(value);
    }
    if (typeof offset === 'undefined') {
      offset = 0;
    }
    var len = length;
    if (typeof len === 'undefined') {
      len = value.byteLength - offset;
    }
    if (offset >= value.byteLength) {
      throw new RangeError('\'offset\' is out of bounds');
    }
    if (len > value.byteLength - offset) {
      throw new RangeError('\'length\' is out of bounds');
    }
    return new Buffer(value.slice(offset, offset + len));
  }
  if (Buffer.isBuffer(value)) {
    var out = new Buffer(value.length);
    value.copy(out, 0, 0, value.length);
    return out;
  }
  if (value) {
    if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
      return new Buffer(value);
    }
    if (value.type === 'Buffer' && Array.isArray(value.data)) {
      return new Buffer(value.data);
    }
  }
 
  throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
}
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
  if (typeof Buffer.allocUnsafeSlow === 'function') {
    return Buffer.allocUnsafeSlow(size);
  }
  if (typeof size !== 'number') {
    throw new TypeError('size must be a number');
  }
  if (size >= MAX_LEN) {
    throw new RangeError('size is too large');
  }
  return new SlowBuffer(size);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/core-util-is/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/core-util-is/lib/

Statements: 63.83% (30 / 47)      Branches: 0% (0 / 12)      Functions: 0% (0 / 15)      Lines: 63.83% (30 / 47)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/core-util-is/lib/
File Statements Branches Functions Lines
util.js 63.83% (30 / 47) 0% (0 / 12) 0% (0 / 15) 63.83% (30 / 47)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

Statements: 63.83% (30 / 47)      Branches: 0% (0 / 12)      Functions: 0% (0 / 15)      Lines: 63.83% (30 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109                                                1           1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1               1   1   1        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
 
function isArray(arg) {
  if (Array.isArray) {
    return Array.isArray(arg);
  }
  return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
 
function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
 
function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;
 
function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
 
function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;
 
function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;
 
function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
 
function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;
 
function isRegExp(re) {
  return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
 
function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
 
function isDate(d) {
  return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
 
function isError(e) {
  return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
 
function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;
 
function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
 
exports.isBuffer = Buffer.isBuffer;
 
function objectToString(o) {
  return Object.prototype.toString.call(o);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/isarray/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/isarray/

Statements: 66.67% (2 / 3)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/isarray/
File Statements Branches Functions Lines
index.js 66.67% (2 / 3) 50% (1 / 2) 0% (0 / 1) 66.67% (2 / 3)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/isarray/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/isarray/index.js

Statements: 66.67% (2 / 3)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 6 71   1        
var toString = {}.toString;
 
module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/process-nextick-args/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/process-nextick-args/

Statements: 13.64% (3 / 22)      Branches: 28.57% (4 / 14)      Functions: 0% (0 / 5)      Lines: 13.64% (3 / 22)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/process-nextick-args/
File Statements Branches Functions Lines
index.js 13.64% (3 / 22) 28.57% (4 / 14) 0% (0 / 5) 13.64% (3 / 22)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/process-nextick-args/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/process-nextick-args/index.js

Statements: 13.64% (3 / 22)      Branches: 28.57% (4 / 14)      Functions: 0% (0 / 5)      Lines: 13.64% (3 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45    1         1     1                                                                    
'use strict';
 
Iif (!process.version ||
    process.version.indexOf('v0.') === 0 ||
    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  module.exports = nextTick;
} else {
  module.exports = process.nextTick;
}
 
function nextTick(fn, arg1, arg2, arg3) {
  if (typeof fn !== 'function') {
    throw new TypeError('"callback" argument must be a function');
  }
  var len = arguments.length;
  var args, i;
  switch (len) {
  case 0:
  case 1:
    return process.nextTick(fn);
  case 2:
    return process.nextTick(function afterTickOne() {
      fn.call(null, arg1);
    });
  case 3:
    return process.nextTick(function afterTickTwo() {
      fn.call(null, arg1, arg2);
    });
  case 4:
    return process.nextTick(function afterTickThree() {
      fn.call(null, arg1, arg2, arg3);
    });
  default:
    args = new Array(len - 1);
    i = 0;
    while (i < args.length) {
      args[i++] = arguments[i];
    }
    return process.nextTick(function afterTick() {
      fn.apply(null, args);
    });
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/util-deprecate/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/util-deprecate/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/util-deprecate/
File Statements Branches Functions Lines
node.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/util-deprecate/node.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readable-stream/node_modules/util-deprecate/node.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8          1    
 
/**
 * For Node.js, simply re-export the core `util.deprecate` function.
 */
 
module.exports = require('util').deprecate;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readdir-scoped-modules/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readdir-scoped-modules/

Statements: 21.95% (9 / 41)      Branches: 0% (0 / 15)      Functions: 0% (0 / 11)      Lines: 21.95% (9 / 41)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/readdir-scoped-modules/
File Statements Branches Functions Lines
readdir.js 21.95% (9 / 41) 0% (0 / 15) 0% (0 / 11) 21.95% (9 / 41)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readdir-scoped-modules/readdir.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/readdir-scoped-modules/readdir.js

Statements: 21.95% (9 / 41)      Branches: 0% (0 / 15)      Functions: 0% (0 / 11)      Lines: 21.95% (9 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 731 1 1 1 1   1   1                                           1                                           1                                        
var fs = require ('graceful-fs')
var dz = require ('dezalgo')
var once = require ('once')
var path = require ('path')
var debug = require ('debuglog') ('rds')
 
module . exports = readdir
 
function readdir (dir, cb) {
  fs . readdir (dir, function (er, kids) {
    if (er)
      return cb (er)
 
    debug ('dir=%j, kids=%j', dir, kids)
    readScopes (dir, kids, function (er, data) {
      if (er)
        return cb (er)
 
      // Sort for bonus consistency points
      data = data . sort (function (a, b) {
        return a > b ? 1 : -1
      })
 
      return cb (null, data)
    })
  })
}
 
// Turn [ 'a', '@scope' ] into
// ['a', '@scope/foo', '@scope/bar']
function readScopes (root, kids, cb) {
  var scopes = kids . filter (function (kid) {
    return kid . charAt (0) === '@'
  })
 
  kids = kids . filter (function (kid) {
    return kid . charAt (0) !== '@'
  })
 
  debug ('scopes=%j', scopes)
 
  if (scopes . length === 0)
    dz (cb) (null, kids) // prevent maybe-sync zalgo release
 
  cb = once (cb)
  var l = scopes . length
  scopes . forEach (function (scope) {
    var scopedir = path . resolve (root, scope)
    debug ('root=%j scope=%j scopedir=%j', root, scope, scopedir)
    fs . readdir (scopedir, then . bind (null, scope))
  })
 
  function then (scope, er, scopekids) {
    if (er)
      return cb (er)
 
    // XXX: Not sure how old this node bug is. Maybe superstition?
    scopekids = scopekids . filter (function (scopekid) {
      return !(scopekid === '.' || scopekid === '..' || !scopekid)
    })
 
    kids . push . apply (kids, scopekids . map (function (scopekid) {
      return scope + '/' + scopekid
    }))
 
    debug ('scope=%j scopekids=%j kids=%j', scope, scopekids, kids)
 
    if (--l === 0)
      cb (null, kids)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/realize-package-specifier/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/realize-package-specifier/

Statements: 18.18% (6 / 33)      Branches: 0% (0 / 29)      Functions: 0% (0 / 4)      Lines: 22.22% (6 / 27)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/realize-package-specifier/
File Statements Branches Functions Lines
index.js 18.18% (6 / 33) 0% (0 / 29) 0% (0 / 4) 22.22% (6 / 27)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/realize-package-specifier/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/realize-package-specifier/index.js

Statements: 18.18% (6 / 33)      Branches: 0% (0 / 29)      Functions: 0% (0 / 4)      Lines: 22.22% (6 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43  1 1 1 1   1                                         1                              
"use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")
 
module.exports = function (spec, where, cb) {
  if (where instanceof Function) { cb = where; where = null }
  if (where == null) where = "."
  cb = dz(cb)
  try {
    var dep = npa(spec)
  }
  catch (e) {
    return cb(e)
  }
  if ((dep.type == "range" || dep.type == "version") && dep.name != dep.raw) return cb(null, dep)
  var specpath = dep.type == "local"
               ? path.resolve(where, dep.spec)
               : path.resolve(where, dep.rawSpec? dep.rawSpec: dep.name)
  fs.stat(specpath, function (er, s) {
    if (er) return finalize()
    if (!s.isDirectory()) return finalize("local")
    fs.stat(path.join(specpath, "package.json"), function (er) {
      finalize(er ? null : "directory")
    })
  })
  function finalize(type) {
    if (type != null && type != dep.type) {
      dep.type = type
      if (! dep.rawSpec) {
        dep.rawSpec = dep.name
        dep.name = null
      }
    }
    if (dep.type == "local" || dep.type == "directory") {
      dep.spec = path.resolve(specpath)
    }
    cb(null, dep)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/

Statements: 7.39% (66 / 893)      Branches: 0.15% (1 / 661)      Functions: 1.2% (1 / 83)      Lines: 7.47% (66 / 884)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/
File Statements Branches Functions Lines
index.js 30.26% (23 / 76) 0% (0 / 28) 7.69% (1 / 13) 30.26% (23 / 76)
request.js 5.26% (43 / 817) 0.16% (1 / 633) 0% (0 / 70) 5.32% (43 / 808)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/index.js

Statements: 30.26% (23 / 76)      Branches: 0% (0 / 28)      Functions: 7.69% (1 / 13)      Lines: 30.26% (23 / 76)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158                                1       1       1                                   1                           1 7 7               1 1 1 1 1 1 1   1       1       1                                           1                                             1                             1 1 1     1                    
// Copyright 2010-2012 Mikeal Rogers
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
 
'use strict'
 
var extend                = require('extend')
  , cookies               = require('./lib/cookies')
  , helpers               = require('./lib/helpers')
 
var paramsHaveRequestBody = helpers.paramsHaveRequestBody
 
 
// organize params for patch, post, put, head, del
function initParams(uri, options, callback) {
  if (typeof options === 'function') {
    callback = options
  }
 
  var params = {}
  if (typeof options === 'object') {
    extend(params, options, {uri: uri})
  } else if (typeof uri === 'string') {
    extend(params, {uri: uri})
  } else {
    extend(params, uri)
  }
 
  params.callback = callback || params.callback
  return params
}
 
function request (uri, options, callback) {
  if (typeof uri === 'undefined') {
    throw new Error('undefined is not a valid uri or options object.')
  }
 
  var params = initParams(uri, options, callback)
 
  if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
    throw new Error('HTTP HEAD requests MUST NOT include a request body.')
  }
 
  return new request.Request(params)
}
 
function verbFunc (verb) {
  var method = verb.toUpperCase()
  return function (uri, options, callback) {
    var params = initParams(uri, options, callback)
    params.method = method
    return request(params, params.callback)
  }
}
 
// define like this to please codeintel/intellisense IDEs
request.get = verbFunc('get')
request.head = verbFunc('head')
request.post = verbFunc('post')
request.put = verbFunc('put')
request.patch = verbFunc('patch')
request.del = verbFunc('delete')
request['delete'] = verbFunc('delete')
 
request.jar = function (store) {
  return cookies.jar(store)
}
 
request.cookie = function (str) {
  return cookies.parse(str)
}
 
function wrapRequestMethod (method, options, requester, verb) {
 
  return function (uri, opts, callback) {
    var params = initParams(uri, opts, callback)
 
    var target = {}
    extend(true, target, options, params)
 
    target.pool = params.pool || options.pool
 
    if (verb) {
      target.method = verb.toUpperCase()
    }
 
    if (typeof requester === 'function') {
      method = requester
    }
 
    return method(target, target.callback)
  }
}
 
request.defaults = function (options, requester) {
  var self = this
 
  options = options || {}
 
  if (typeof options === 'function') {
    requester = options
    options = {}
  }
 
  var defaults      = wrapRequestMethod(self, options, requester)
 
  var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
  verbs.forEach(function(verb) {
    defaults[verb]  = wrapRequestMethod(self[verb], options, requester, verb)
  })
 
  defaults.cookie   = wrapRequestMethod(self.cookie, options, requester)
  defaults.jar      = self.jar
  defaults.defaults = self.defaults
  return defaults
}
 
request.forever = function (agentOptions, optionsArg) {
  var options = {}
  if (optionsArg) {
    extend(options, optionsArg)
  }
  if (agentOptions) {
    options.agentOptions = agentOptions
  }
 
  options.forever = true
  return request.defaults(options)
}
 
// Exports
 
module.exports = request
request.Request = require('./request')
request.initParams = initParams
 
// Backwards compatibility for request.debug
Object.defineProperty(request, 'debug', {
  enumerable : true,
  get : function() {
    return request.Request.debug
  },
  set : function(debug) {
    request.Request.debug = debug
  }
})
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/request.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/request.js

Statements: 5.26% (43 / 817)      Branches: 0.16% (1 / 633)      Functions: 0% (0 / 70)      Lines: 5.32% (43 / 808)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567    1                                                             1                 1   1                           1                                 1                   1                   1                                                                         1     1 1         1   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                       1                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                       1                           1                                                                             1                                                         1                                       1                     1                                                                       1                                   1                             1             1                                                                                                                     1                               1       1               1                                                                       1                                     1                     1                           1               1               1                 1     1         1 1    
'use strict'
 
var http = require('http')
  , https = require('https')
  , url = require('url')
  , util = require('util')
  , stream = require('stream')
  , zlib = require('zlib')
  , hawk = require('hawk')
  , aws2 = require('aws-sign2')
  , aws4 = require('aws4')
  , httpSignature = require('http-signature')
  , mime = require('mime-types')
  , stringstream = require('stringstream')
  , caseless = require('caseless')
  , ForeverAgent = require('forever-agent')
  , FormData = require('form-data')
  , extend = require('extend')
  , isstream = require('isstream')
  , isTypedArray = require('is-typedarray').strict
  , helpers = require('./lib/helpers')
  , cookies = require('./lib/cookies')
  , getProxyFromURI = require('./lib/getProxyFromURI')
  , Querystring = require('./lib/querystring').Querystring
  , Har = require('./lib/har').Har
  , Auth = require('./lib/auth').Auth
  , OAuth = require('./lib/oauth').OAuth
  , Multipart = require('./lib/multipart').Multipart
  , Redirect = require('./lib/redirect').Redirect
  , Tunnel = require('./lib/tunnel').Tunnel
  , now = require('performance-now')
  , Buffer = require('safe-buffer').Buffer
 
var safeStringify = helpers.safeStringify
  , isReadStream = helpers.isReadStream
  , toBase64 = helpers.toBase64
  , defer = helpers.defer
  , copy = helpers.copy
  , version = helpers.version
  , globalCookieJar = cookies.jar()
 
 
var globalPool = {}
 
function filterForNonReserved(reserved, options) {
  // Filter out properties that are not reserved.
  // Reserved values are passed in at call site.
 
  var object = {}
  for (var i in options) {
    var notReserved = (reserved.indexOf(i) === -1)
    if (notReserved) {
      object[i] = options[i]
    }
  }
  return object
}
 
function filterOutReservedFunctions(reserved, options) {
  // Filter out properties that are functions and are reserved.
  // Reserved values are passed in at call site.
 
  var object = {}
  for (var i in options) {
    var isReserved = !(reserved.indexOf(i) === -1)
    var isFunction = (typeof options[i] === 'function')
    if (!(isReserved && isFunction)) {
      object[i] = options[i]
    }
  }
  return object
 
}
 
// Return a simpler request object to allow serialization
function requestToJSON() {
  var self = this
  return {
    uri: self.uri,
    method: self.method,
    headers: self.headers
  }
}
 
// Return a simpler response object to allow serialization
function responseToJSON() {
  var self = this
  return {
    statusCode: self.statusCode,
    body: self.body,
    headers: self.headers,
    request: requestToJSON.call(self.request)
  }
}
 
function Request (options) {
  // if given the method property in options, set property explicitMethod to true
 
  // extend the Request instance with any non-reserved properties
  // remove any reserved functions from the options object
  // set Request instance to be readable and writable
  // call init
 
  var self = this
 
  // start with HAR, then override with additional options
  if (options.har) {
    self._har = new Har(self)
    options = self._har.options(options)
  }
 
  stream.Stream.call(self)
  var reserved = Object.keys(Request.prototype)
  var nonReserved = filterForNonReserved(reserved, options)
 
  extend(self, nonReserved)
  options = filterOutReservedFunctions(reserved, options)
 
  self.readable = true
  self.writable = true
  if (options.method) {
    self.explicitMethod = true
  }
  self._qs = new Querystring(self)
  self._auth = new Auth(self)
  self._oauth = new OAuth(self)
  self._multipart = new Multipart(self)
  self._redirect = new Redirect(self)
  self._tunnel = new Tunnel(self)
  self.init(options)
}
 
util.inherits(Request, stream.Stream)
 
// Debugging
Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
function debug() {
  if (Request.debug) {
    console.error('REQUEST %s', util.format.apply(util, arguments))
  }
}
Request.prototype.debug = debug
 
Request.prototype.init = function (options) {
  // init() contains all the code to setup the request object.
  // the actual outgoing request is not started until start() is called
  // this function is called from both the constructor and on redirect.
  var self = this
  if (!options) {
    options = {}
  }
  self.headers = self.headers ? copy(self.headers) : {}
 
  // Delete headers with value undefined since they break
  // ClientRequest.OutgoingMessage.setHeader in node 0.12
  for (var headerName in self.headers) {
    if (typeof self.headers[headerName] === 'undefined') {
      delete self.headers[headerName]
    }
  }
 
  caseless.httpify(self, self.headers)
 
  if (!self.method) {
    self.method = options.method || 'GET'
  }
  if (!self.localAddress) {
    self.localAddress = options.localAddress
  }
 
  self._qs.init(options)
 
  debug(options)
  if (!self.pool && self.pool !== false) {
    self.pool = globalPool
  }
  self.dests = self.dests || []
  self.__isRequestRequest = true
 
  // Protect against double callback
  if (!self._callback && self.callback) {
    self._callback = self.callback
    self.callback = function () {
      if (self._callbackCalled) {
        return // Print a warning maybe?
      }
      self._callbackCalled = true
      self._callback.apply(self, arguments)
    }
    self.on('error', self.callback.bind())
    self.on('complete', self.callback.bind(self, null))
  }
 
  // People use this property instead all the time, so support it
  if (!self.uri && self.url) {
    self.uri = self.url
    delete self.url
  }
 
  // If there's a baseUrl, then use it as the base URL (i.e. uri must be
  // specified as a relative path and is appended to baseUrl).
  if (self.baseUrl) {
    if (typeof self.baseUrl !== 'string') {
      return self.emit('error', new Error('options.baseUrl must be a string'))
    }
 
    if (typeof self.uri !== 'string') {
      return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
    }
 
    if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
      return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
    }
 
    // Handle all cases to make sure that there's only one slash between
    // baseUrl and uri.
    var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
    var uriStartsWithSlash = self.uri.indexOf('/') === 0
 
    if (baseUrlEndsWithSlash && uriStartsWithSlash) {
      self.uri = self.baseUrl + self.uri.slice(1)
    } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
      self.uri = self.baseUrl + self.uri
    } else if (self.uri === '') {
      self.uri = self.baseUrl
    } else {
      self.uri = self.baseUrl + '/' + self.uri
    }
    delete self.baseUrl
  }
 
  // A URI is needed by this point, emit error if we haven't been able to get one
  if (!self.uri) {
    return self.emit('error', new Error('options.uri is a required argument'))
  }
 
  // If a string URI/URL was given, parse it into a URL object
  if (typeof self.uri === 'string') {
    self.uri = url.parse(self.uri)
  }
 
  // Some URL objects are not from a URL parsed string and need href added
  if (!self.uri.href) {
    self.uri.href = url.format(self.uri)
  }
 
  // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
  if (self.uri.protocol === 'unix:') {
    return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
  }
 
  // Support Unix Sockets
  if (self.uri.host === 'unix') {
    self.enableUnixSocket()
  }
 
  if (self.strictSSL === false) {
    self.rejectUnauthorized = false
  }
 
  if (!self.uri.pathname) {self.uri.pathname = '/'}
 
  if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
    // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
    // Detect and reject it as soon as possible
    var faultyUri = url.format(self.uri)
    var message = 'Invalid URI "' + faultyUri + '"'
    if (Object.keys(options).length === 0) {
      // No option ? This can be the sign of a redirect
      // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
      // they should be warned that it can be caused by a redirection (can save some hair)
      message += '. This can be caused by a crappy redirection.'
    }
    // This error was fatal
    self.abort()
    return self.emit('error', new Error(message))
  }
 
  if (!self.hasOwnProperty('proxy')) {
    self.proxy = getProxyFromURI(self.uri)
  }
 
  self.tunnel = self._tunnel.isEnabled()
  if (self.proxy) {
    self._tunnel.setup(options)
  }
 
  self._redirect.onRequest(options)
 
  self.setHost = false
  if (!self.hasHeader('host')) {
    var hostHeaderName = self.originalHostHeaderName || 'host'
    // When used with an IPv6 address, `host` will provide
    // the correct bracketed format, unlike using `hostname` and
    // optionally adding the `port` when necessary.
    self.setHeader(hostHeaderName, self.uri.host)
    self.setHost = true
  }
 
  self.jar(self._jar || options.jar)
 
  if (!self.uri.port) {
    if (self.uri.protocol === 'http:') {self.uri.port = 80}
    else if (self.uri.protocol === 'https:') {self.uri.port = 443}
  }
 
  if (self.proxy && !self.tunnel) {
    self.port = self.proxy.port
    self.host = self.proxy.hostname
  } else {
    self.port = self.uri.port
    self.host = self.uri.hostname
  }
 
  if (options.form) {
    self.form(options.form)
  }
 
  if (options.formData) {
    var formData = options.formData
    var requestForm = self.form()
    var appendFormValue = function (key, value) {
      if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
        requestForm.append(key, value.value, value.options)
      } else {
        requestForm.append(key, value)
      }
    }
    for (var formKey in formData) {
      if (formData.hasOwnProperty(formKey)) {
        var formValue = formData[formKey]
        if (formValue instanceof Array) {
          for (var j = 0; j < formValue.length; j++) {
            appendFormValue(formKey, formValue[j])
          }
        } else {
          appendFormValue(formKey, formValue)
        }
      }
    }
  }
 
  if (options.qs) {
    self.qs(options.qs)
  }
 
  if (self.uri.path) {
    self.path = self.uri.path
  } else {
    self.path = self.uri.pathname + (self.uri.search || '')
  }
 
  if (self.path.length === 0) {
    self.path = '/'
  }
 
  // Auth must happen last in case signing is dependent on other headers
  if (options.aws) {
    self.aws(options.aws)
  }
 
  if (options.hawk) {
    self.hawk(options.hawk)
  }
 
  if (options.httpSignature) {
    self.httpSignature(options.httpSignature)
  }
 
  if (options.auth) {
    if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
      options.auth.user = options.auth.username
    }
    if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
      options.auth.pass = options.auth.password
    }
 
    self.auth(
      options.auth.user,
      options.auth.pass,
      options.auth.sendImmediately,
      options.auth.bearer
    )
  }
 
  if (self.gzip && !self.hasHeader('accept-encoding')) {
    self.setHeader('accept-encoding', 'gzip, deflate')
  }
 
  if (self.uri.auth && !self.hasHeader('authorization')) {
    var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
    self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
  }
 
  if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
    var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
    var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
    self.setHeader('proxy-authorization', authHeader)
  }
 
  if (self.proxy && !self.tunnel) {
    self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
  }
 
  if (options.json) {
    self.json(options.json)
  }
  if (options.multipart) {
    self.multipart(options.multipart)
  }
 
  if (options.time) {
    self.timing = true
 
    // NOTE: elapsedTime is deprecated in favor of .timings
    self.elapsedTime = self.elapsedTime || 0
  }
 
  function setContentLength () {
    if (isTypedArray(self.body)) {
      self.body = Buffer.from(self.body)
    }
 
    if (!self.hasHeader('content-length')) {
      var length
      if (typeof self.body === 'string') {
        length = Buffer.byteLength(self.body)
      }
      else if (Array.isArray(self.body)) {
        length = self.body.reduce(function (a, b) {return a + b.length}, 0)
      }
      else {
        length = self.body.length
      }
 
      if (length) {
        self.setHeader('content-length', length)
      } else {
        self.emit('error', new Error('Argument error, options.body.'))
      }
    }
  }
  if (self.body && !isstream(self.body)) {
    setContentLength()
  }
 
  if (options.oauth) {
    self.oauth(options.oauth)
  } else if (self._oauth.params && self.hasHeader('authorization')) {
    self.oauth(self._oauth.params)
  }
 
  var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
    , defaultModules = {'http:':http, 'https:':https}
    , httpModules = self.httpModules || {}
 
  self.httpModule = httpModules[protocol] || defaultModules[protocol]
 
  if (!self.httpModule) {
    return self.emit('error', new Error('Invalid protocol: ' + protocol))
  }
 
  if (options.ca) {
    self.ca = options.ca
  }
 
  if (!self.agent) {
    if (options.agentOptions) {
      self.agentOptions = options.agentOptions
    }
 
    if (options.agentClass) {
      self.agentClass = options.agentClass
    } else if (options.forever) {
      var v = version()
      // use ForeverAgent in node 0.10- only
      if (v.major === 0 && v.minor <= 10) {
        self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
      } else {
        self.agentClass = self.httpModule.Agent
        self.agentOptions = self.agentOptions || {}
        self.agentOptions.keepAlive = true
      }
    } else {
      self.agentClass = self.httpModule.Agent
    }
  }
 
  if (self.pool === false) {
    self.agent = false
  } else {
    self.agent = self.agent || self.getNewAgent()
  }
 
  self.on('pipe', function (src) {
    if (self.ntick && self._started) {
      self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
    }
    self.src = src
    if (isReadStream(src)) {
      if (!self.hasHeader('content-type')) {
        self.setHeader('content-type', mime.lookup(src.path))
      }
    } else {
      if (src.headers) {
        for (var i in src.headers) {
          if (!self.hasHeader(i)) {
            self.setHeader(i, src.headers[i])
          }
        }
      }
      if (self._json && !self.hasHeader('content-type')) {
        self.setHeader('content-type', 'application/json')
      }
      if (src.method && !self.explicitMethod) {
        self.method = src.method
      }
    }
 
    // self.on('pipe', function () {
    //   console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
    // })
  })
 
  defer(function () {
    if (self._aborted) {
      return
    }
 
    var end = function () {
      if (self._form) {
        if (!self._auth.hasAuth) {
          self._form.pipe(self)
        }
        else if (self._auth.hasAuth && self._auth.sentAuth) {
          self._form.pipe(self)
        }
      }
      if (self._multipart && self._multipart.chunked) {
        self._multipart.body.pipe(self)
      }
      if (self.body) {
        if (isstream(self.body)) {
          self.body.pipe(self)
        } else {
          setContentLength()
          if (Array.isArray(self.body)) {
            self.body.forEach(function (part) {
              self.write(part)
            })
          } else {
            self.write(self.body)
          }
          self.end()
        }
      } else if (self.requestBodyStream) {
        console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
        self.requestBodyStream.pipe(self)
      } else if (!self.src) {
        if (self._auth.hasAuth && !self._auth.sentAuth) {
          self.end()
          return
        }
        if (self.method !== 'GET' && typeof self.method !== 'undefined') {
          self.setHeader('content-length', 0)
        }
        self.end()
      }
    }
 
    if (self._form && !self.hasHeader('content-length')) {
      // Before ending the request, we had to compute the length of the whole form, asyncly
      self.setHeader(self._form.getHeaders(), true)
      self._form.getLength(function (err, length) {
        if (!err && !isNaN(length)) {
          self.setHeader('content-length', length)
        }
        end()
      })
    } else {
      end()
    }
 
    self.ntick = true
  })
 
}
 
Request.prototype.getNewAgent = function () {
  var self = this
  var Agent = self.agentClass
  var options = {}
  if (self.agentOptions) {
    for (var i in self.agentOptions) {
      options[i] = self.agentOptions[i]
    }
  }
  if (self.ca) {
    options.ca = self.ca
  }
  if (self.ciphers) {
    options.ciphers = self.ciphers
  }
  if (self.secureProtocol) {
    options.secureProtocol = self.secureProtocol
  }
  if (self.secureOptions) {
    options.secureOptions = self.secureOptions
  }
  if (typeof self.rejectUnauthorized !== 'undefined') {
    options.rejectUnauthorized = self.rejectUnauthorized
  }
 
  if (self.cert && self.key) {
    options.key = self.key
    options.cert = self.cert
  }
 
  if (self.pfx) {
    options.pfx = self.pfx
  }
 
  if (self.passphrase) {
    options.passphrase = self.passphrase
  }
 
  var poolKey = ''
 
  // different types of agents are in different pools
  if (Agent !== self.httpModule.Agent) {
    poolKey += Agent.name
  }
 
  // ca option is only relevant if proxy or destination are https
  var proxy = self.proxy
  if (typeof proxy === 'string') {
    proxy = url.parse(proxy)
  }
  var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
 
  if (isHttps) {
    if (options.ca) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.ca
    }
 
    if (typeof options.rejectUnauthorized !== 'undefined') {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.rejectUnauthorized
    }
 
    if (options.cert) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
    }
 
    if (options.pfx) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.pfx.toString('ascii')
    }
 
    if (options.ciphers) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.ciphers
    }
 
    if (options.secureProtocol) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.secureProtocol
    }
 
    if (options.secureOptions) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.secureOptions
    }
  }
 
  if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
    // not doing anything special.  Use the globalAgent
    return self.httpModule.globalAgent
  }
 
  // we're using a stored agent.  Make sure it's protocol-specific
  poolKey = self.uri.protocol + poolKey
 
  // generate a new agent for this setting if none yet exists
  if (!self.pool[poolKey]) {
    self.pool[poolKey] = new Agent(options)
    // properly set maxSockets on new agents
    if (self.pool.maxSockets) {
      self.pool[poolKey].maxSockets = self.pool.maxSockets
    }
  }
 
  return self.pool[poolKey]
}
 
Request.prototype.start = function () {
  // start() is called once we are ready to send the outgoing HTTP request.
  // this is usually called on the first write(), end() or on nextTick()
  var self = this
 
  if (self.timing) {
    // All timings will be relative to this request's startTime.  In order to do this,
    // we need to capture the wall-clock start time (via Date), immediately followed
    // by the high-resolution timer (via now()).  While these two won't be set
    // at the _exact_ same time, they should be close enough to be able to calculate
    // high-resolution, monotonically non-decreasing timestamps relative to startTime.
    var startTime = new Date().getTime()
    var startTimeNow = now()
  }
 
  if (self._aborted) {
    return
  }
 
  self._started = true
  self.method = self.method || 'GET'
  self.href = self.uri.href
 
  if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
    self.setHeader('content-length', self.src.stat.size)
  }
  if (self._aws) {
    self.aws(self._aws, true)
  }
 
  // We have a method named auth, which is completely different from the http.request
  // auth option.  If we don't remove it, we're gonna have a bad time.
  var reqOptions = copy(self)
  delete reqOptions.auth
 
  debug('make request', self.uri.href)
 
  // node v6.8.0 now supports a `timeout` value in `http.request()`, but we
  // should delete it for now since we handle timeouts manually for better
  // consistency with node versions before v6.8.0
  delete reqOptions.timeout
 
  try {
    self.req = self.httpModule.request(reqOptions)
  } catch (err) {
    self.emit('error', err)
    return
  }
 
  if (self.timing) {
    self.startTime = startTime
    self.startTimeNow = startTimeNow
 
    // Timing values will all be relative to startTime (by comparing to startTimeNow
    // so we have an accurate clock)
    self.timings = {}
  }
 
  var timeout
  if (self.timeout && !self.timeoutTimer) {
    if (self.timeout < 0) {
      timeout = 0
    } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
      timeout = self.timeout
    }
  }
 
  self.req.on('response', self.onRequestResponse.bind(self))
  self.req.on('error', self.onRequestError.bind(self))
  self.req.on('drain', function() {
    self.emit('drain')
  })
  self.req.on('socket', function(socket) {
    // `._connecting` was the old property which was made public in node v6.1.0
    var isConnecting = socket._connecting || socket.connecting
    if (self.timing) {
      self.timings.socket = now() - self.startTimeNow
 
      if (isConnecting) {
        var onLookupTiming = function() {
          self.timings.lookup = now() - self.startTimeNow
        }
 
        var onConnectTiming = function() {
          self.timings.connect = now() - self.startTimeNow
        }
 
        socket.once('lookup', onLookupTiming)
        socket.once('connect', onConnectTiming)
 
        // clean up timing event listeners if needed on error
        self.req.once('error', function() {
          socket.removeListener('lookup', onLookupTiming)
          socket.removeListener('connect', onConnectTiming)
        })
      }
    }
 
    var setReqTimeout = function() {
      // This timeout sets the amount of time to wait *between* bytes sent
      // from the server once connected.
      //
      // In particular, it's useful for erroring if the server fails to send
      // data halfway through streaming a response.
      self.req.setTimeout(timeout, function () {
        if (self.req) {
          self.abort()
          var e = new Error('ESOCKETTIMEDOUT')
          e.code = 'ESOCKETTIMEDOUT'
          e.connect = false
          self.emit('error', e)
        }
      })
    }
    if (timeout !== undefined) {
      // Only start the connection timer if we're actually connecting a new
      // socket, otherwise if we're already connected (because this is a
      // keep-alive connection) do not bother. This is important since we won't
      // get a 'connect' event for an already connected socket.
      if (isConnecting) {
        var onReqSockConnect = function() {
          socket.removeListener('connect', onReqSockConnect)
          clearTimeout(self.timeoutTimer)
          self.timeoutTimer = null
          setReqTimeout()
        }
 
        socket.on('connect', onReqSockConnect)
 
        self.req.on('error', function(err) {
          socket.removeListener('connect', onReqSockConnect)
        })
 
        // Set a timeout in memory - this block will throw if the server takes more
        // than `timeout` to write the HTTP status and headers (corresponding to
        // the on('response') event on the client). NB: this measures wall-clock
        // time, not the time between bytes sent by the server.
        self.timeoutTimer = setTimeout(function () {
          socket.removeListener('connect', onReqSockConnect)
          self.abort()
          var e = new Error('ETIMEDOUT')
          e.code = 'ETIMEDOUT'
          e.connect = true
          self.emit('error', e)
        }, timeout)
      } else {
        // We're already connected
        setReqTimeout()
      }
    }
    self.emit('socket', socket)
  })
 
  self.emit('request', self.req)
}
 
Request.prototype.onRequestError = function (error) {
  var self = this
  if (self._aborted) {
    return
  }
  if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
      && self.agent.addRequestNoreuse) {
    self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
    self.start()
    self.req.end()
    return
  }
  if (self.timeout && self.timeoutTimer) {
    clearTimeout(self.timeoutTimer)
    self.timeoutTimer = null
  }
  self.emit('error', error)
}
 
Request.prototype.onRequestResponse = function (response) {
  var self = this
 
  if (self.timing) {
    self.timings.response = now() - self.startTimeNow
  }
 
  debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
  response.on('end', function() {
    if (self.timing) {
      self.timings.end = now() - self.startTimeNow
      response.timingStart = self.startTime
 
      // fill in the blanks for any periods that didn't trigger, such as
      // no lookup or connect due to keep alive
      if (!self.timings.socket) {
        self.timings.socket = 0
      }
      if (!self.timings.lookup) {
        self.timings.lookup = self.timings.socket
      }
      if (!self.timings.connect) {
        self.timings.connect = self.timings.lookup
      }
      if (!self.timings.response) {
        self.timings.response = self.timings.connect
      }
 
      debug('elapsed time', self.timings.end)
 
      // elapsedTime includes all redirects
      self.elapsedTime += Math.round(self.timings.end)
 
      // NOTE: elapsedTime is deprecated in favor of .timings
      response.elapsedTime = self.elapsedTime
 
      // timings is just for the final fetch
      response.timings = self.timings
 
      // pre-calculate phase timings as well
      response.timingPhases = {
        wait: self.timings.socket,
        dns: self.timings.lookup - self.timings.socket,
        tcp: self.timings.connect - self.timings.lookup,
        firstByte: self.timings.response - self.timings.connect,
        download: self.timings.end - self.timings.response,
        total: self.timings.end
      }
    }
    debug('response end', self.uri.href, response.statusCode, response.headers)
  })
 
  if (self._aborted) {
    debug('aborted', self.uri.href)
    response.resume()
    return
  }
 
  self.response = response
  response.request = self
  response.toJSON = responseToJSON
 
  // XXX This is different on 0.10, because SSL is strict by default
  if (self.httpModule === https &&
      self.strictSSL && (!response.hasOwnProperty('socket') ||
      !response.socket.authorized)) {
    debug('strict ssl error', self.uri.href)
    var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
    self.emit('error', new Error('SSL Error: ' + sslErr))
    return
  }
 
  // Save the original host before any redirect (if it changes, we need to
  // remove any authorization headers).  Also remember the case of the header
  // name because lots of broken servers expect Host instead of host and we
  // want the caller to be able to specify this.
  self.originalHost = self.getHeader('host')
  if (!self.originalHostHeaderName) {
    self.originalHostHeaderName = self.hasHeader('host')
  }
  if (self.setHost) {
    self.removeHeader('host')
  }
  if (self.timeout && self.timeoutTimer) {
    clearTimeout(self.timeoutTimer)
    self.timeoutTimer = null
  }
 
  var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
  var addCookie = function (cookie) {
    //set the cookie if it's domain in the href's domain.
    try {
      targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
    } catch (e) {
      self.emit('error', e)
    }
  }
 
  response.caseless = caseless(response.headers)
 
  if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
    var headerName = response.caseless.has('set-cookie')
    if (Array.isArray(response.headers[headerName])) {
      response.headers[headerName].forEach(addCookie)
    } else {
      addCookie(response.headers[headerName])
    }
  }
 
  if (self._redirect.onResponse(response)) {
    return // Ignore the rest of the response
  } else {
    // Be a good stream and emit end when the response is finished.
    // Hack to emit end on close because of a core bug that never fires end
    response.on('close', function () {
      if (!self._ended) {
        self.response.emit('end')
      }
    })
 
    response.once('end', function () {
      self._ended = true
    })
 
    var noBody = function (code) {
      return (
        self.method === 'HEAD'
        // Informational
        || (code >= 100 && code < 200)
        // No Content
        || code === 204
        // Not Modified
        || code === 304
      )
    }
 
    var responseContent
    if (self.gzip && !noBody(response.statusCode)) {
      var contentEncoding = response.headers['content-encoding'] || 'identity'
      contentEncoding = contentEncoding.trim().toLowerCase()
 
      // Be more lenient with decoding compressed responses, since (very rarely)
      // servers send slightly invalid gzip responses that are still accepted
      // by common browsers.
      // Always using Z_SYNC_FLUSH is what cURL does.
      var zlibOptions = {
        flush: zlib.Z_SYNC_FLUSH
      , finishFlush: zlib.Z_SYNC_FLUSH
      }
 
      if (contentEncoding === 'gzip') {
        responseContent = zlib.createGunzip(zlibOptions)
        response.pipe(responseContent)
      } else if (contentEncoding === 'deflate') {
        responseContent = zlib.createInflate(zlibOptions)
        response.pipe(responseContent)
      } else {
        // Since previous versions didn't check for Content-Encoding header,
        // ignore any invalid values to preserve backwards-compatibility
        if (contentEncoding !== 'identity') {
          debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
        }
        responseContent = response
      }
    } else {
      responseContent = response
    }
 
    if (self.encoding) {
      if (self.dests.length !== 0) {
        console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
      } else if (responseContent.setEncoding) {
        responseContent.setEncoding(self.encoding)
      } else {
        // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
        // zlib streams.
        // If/When support for 0.9.4 is dropped, this should be unnecessary.
        responseContent = responseContent.pipe(stringstream(self.encoding))
      }
    }
 
    if (self._paused) {
      responseContent.pause()
    }
 
    self.responseContent = responseContent
 
    self.emit('response', response)
 
    self.dests.forEach(function (dest) {
      self.pipeDest(dest)
    })
 
    responseContent.on('data', function (chunk) {
      if (self.timing && !self.responseStarted) {
        self.responseStartTime = (new Date()).getTime()
 
        // NOTE: responseStartTime is deprecated in favor of .timings
        response.responseStartTime = self.responseStartTime
      }
      self._destdata = true
      self.emit('data', chunk)
    })
    responseContent.once('end', function (chunk) {
      self.emit('end', chunk)
    })
    responseContent.on('error', function (error) {
      self.emit('error', error)
    })
    responseContent.on('close', function () {self.emit('close')})
 
    if (self.callback) {
      self.readResponseBody(response)
    }
    //if no callback
    else {
      self.on('end', function () {
        if (self._aborted) {
          debug('aborted', self.uri.href)
          return
        }
        self.emit('complete', response)
      })
    }
  }
  debug('finish init function', self.uri.href)
}
 
Request.prototype.readResponseBody = function (response) {
  var self = this
  debug('reading response\'s body')
  var buffers = []
    , bufferLength = 0
    , strings = []
 
  self.on('data', function (chunk) {
    if (!Buffer.isBuffer(chunk)) {
      strings.push(chunk)
    } else if (chunk.length) {
      bufferLength += chunk.length
      buffers.push(chunk)
    }
  })
  self.on('end', function () {
    debug('end event', self.uri.href)
    if (self._aborted) {
      debug('aborted', self.uri.href)
      // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
      // This can lead to leaky behavior if the user retains a reference to the request object.
      buffers = []
      bufferLength = 0
      return
    }
 
    if (bufferLength) {
      debug('has body', self.uri.href, bufferLength)
      response.body = Buffer.concat(buffers, bufferLength)
      if (self.encoding !== null) {
        response.body = response.body.toString(self.encoding)
      }
      // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
      // This can lead to leaky behavior if the user retains a reference to the request object.
      buffers = []
      bufferLength = 0
    } else if (strings.length) {
      // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
      // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
      if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
        strings[0] = strings[0].substring(1)
      }
      response.body = strings.join('')
    }
 
    if (self._json) {
      try {
        response.body = JSON.parse(response.body, self._jsonReviver)
      } catch (e) {
        debug('invalid JSON received', self.uri.href)
      }
    }
    debug('emitting complete', self.uri.href)
    if (typeof response.body === 'undefined' && !self._json) {
      response.body = self.encoding === null ? Buffer.alloc(0) : ''
    }
    self.emit('complete', response, response.body)
  })
}
 
Request.prototype.abort = function () {
  var self = this
  self._aborted = true
 
  if (self.req) {
    self.req.abort()
  }
  else if (self.response) {
    self.response.destroy()
  }
 
  self.emit('abort')
}
 
Request.prototype.pipeDest = function (dest) {
  var self = this
  var response = self.response
  // Called after the response is received
  if (dest.headers && !dest.headersSent) {
    if (response.caseless.has('content-type')) {
      var ctname = response.caseless.has('content-type')
      if (dest.setHeader) {
        dest.setHeader(ctname, response.headers[ctname])
      }
      else {
        dest.headers[ctname] = response.headers[ctname]
      }
    }
 
    if (response.caseless.has('content-length')) {
      var clname = response.caseless.has('content-length')
      if (dest.setHeader) {
        dest.setHeader(clname, response.headers[clname])
      } else {
        dest.headers[clname] = response.headers[clname]
      }
    }
  }
  if (dest.setHeader && !dest.headersSent) {
    for (var i in response.headers) {
      // If the response content is being decoded, the Content-Encoding header
      // of the response doesn't represent the piped content, so don't pass it.
      if (!self.gzip || i !== 'content-encoding') {
        dest.setHeader(i, response.headers[i])
      }
    }
    dest.statusCode = response.statusCode
  }
  if (self.pipefilter) {
    self.pipefilter(response, dest)
  }
}
 
Request.prototype.qs = function (q, clobber) {
  var self = this
  var base
  if (!clobber && self.uri.query) {
    base = self._qs.parse(self.uri.query)
  } else {
    base = {}
  }
 
  for (var i in q) {
    base[i] = q[i]
  }
 
  var qs = self._qs.stringify(base)
 
  if (qs === '') {
    return self
  }
 
  self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
  self.url = self.uri
  self.path = self.uri.path
 
  if (self.uri.host === 'unix') {
    self.enableUnixSocket()
  }
 
  return self
}
Request.prototype.form = function (form) {
  var self = this
  if (form) {
    if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
      self.setHeader('content-type', 'application/x-www-form-urlencoded')
    }
    self.body = (typeof form === 'string')
      ? self._qs.rfc3986(form.toString('utf8'))
      : self._qs.stringify(form).toString('utf8')
    return self
  }
  // create form-data object
  self._form = new FormData()
  self._form.on('error', function(err) {
    err.message = 'form-data: ' + err.message
    self.emit('error', err)
    self.abort()
  })
  return self._form
}
Request.prototype.multipart = function (multipart) {
  var self = this
 
  self._multipart.onRequest(multipart)
 
  if (!self._multipart.chunked) {
    self.body = self._multipart.body
  }
 
  return self
}
Request.prototype.json = function (val) {
  var self = this
 
  if (!self.hasHeader('accept')) {
    self.setHeader('accept', 'application/json')
  }
 
  if (typeof self.jsonReplacer === 'function') {
    self._jsonReplacer = self.jsonReplacer
  }
 
  self._json = true
  if (typeof val === 'boolean') {
    if (self.body !== undefined) {
      if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
        self.body = safeStringify(self.body, self._jsonReplacer)
      } else {
        self.body = self._qs.rfc3986(self.body)
      }
      if (!self.hasHeader('content-type')) {
        self.setHeader('content-type', 'application/json')
      }
    }
  } else {
    self.body = safeStringify(val, self._jsonReplacer)
    if (!self.hasHeader('content-type')) {
      self.setHeader('content-type', 'application/json')
    }
  }
 
  if (typeof self.jsonReviver === 'function') {
    self._jsonReviver = self.jsonReviver
  }
 
  return self
}
Request.prototype.getHeader = function (name, headers) {
  var self = this
  var result, re, match
  if (!headers) {
    headers = self.headers
  }
  Object.keys(headers).forEach(function (key) {
    if (key.length !== name.length) {
      return
    }
    re = new RegExp(name, 'i')
    match = key.match(re)
    if (match) {
      result = headers[key]
    }
  })
  return result
}
Request.prototype.enableUnixSocket = function () {
  // Get the socket & request paths from the URL
  var unixParts = this.uri.path.split(':')
    , host = unixParts[0]
    , path = unixParts[1]
  // Apply unix properties to request
  this.socketPath = host
  this.uri.pathname = path
  this.uri.path = path
  this.uri.host = host
  this.uri.hostname = host
  this.uri.isUnix = true
}
 
 
Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
  var self = this
 
  self._auth.onRequest(user, pass, sendImmediately, bearer)
 
  return self
}
Request.prototype.aws = function (opts, now) {
  var self = this
 
  if (!now) {
    self._aws = opts
    return self
  }
 
  if (opts.sign_version == 4 || opts.sign_version == '4') {
    // use aws4
    var options = {
      host: self.uri.host,
      path: self.uri.path,
      method: self.method,
      headers: {
        'content-type': self.getHeader('content-type') || ''
      },
      body: self.body
    }
    var signRes = aws4.sign(options, {
      accessKeyId: opts.key,
      secretAccessKey: opts.secret,
      sessionToken: opts.session
    })
    self.setHeader('authorization', signRes.headers.Authorization)
    self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
    if (signRes.headers['X-Amz-Security-Token']) {
      self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
    }
  }
  else {
    // default: use aws-sign2
    var date = new Date()
    self.setHeader('date', date.toUTCString())
    var auth =
      { key: opts.key
      , secret: opts.secret
      , verb: self.method.toUpperCase()
      , date: date
      , contentType: self.getHeader('content-type') || ''
      , md5: self.getHeader('content-md5') || ''
      , amazonHeaders: aws2.canonicalizeHeaders(self.headers)
      }
    var path = self.uri.path
    if (opts.bucket && path) {
      auth.resource = '/' + opts.bucket + path
    } else if (opts.bucket && !path) {
      auth.resource = '/' + opts.bucket
    } else if (!opts.bucket && path) {
      auth.resource = path
    } else if (!opts.bucket && !path) {
      auth.resource = '/'
    }
    auth.resource = aws2.canonicalizeResource(auth.resource)
    self.setHeader('authorization', aws2.authorization(auth))
  }
 
  return self
}
Request.prototype.httpSignature = function (opts) {
  var self = this
  httpSignature.signRequest({
    getHeader: function(header) {
      return self.getHeader(header, self.headers)
    },
    setHeader: function(header, value) {
      self.setHeader(header, value)
    },
    method: self.method,
    path: self.path
  }, opts)
  debug('httpSignature authorization', self.getHeader('authorization'))
 
  return self
}
Request.prototype.hawk = function (opts) {
  var self = this
  self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
}
Request.prototype.oauth = function (_oauth) {
  var self = this
 
  self._oauth.onRequest(_oauth)
 
  return self
}
 
Request.prototype.jar = function (jar) {
  var self = this
  var cookies
 
  if (self._redirect.redirectsFollowed === 0) {
    self.originalCookieHeader = self.getHeader('cookie')
  }
 
  if (!jar) {
    // disable cookies
    cookies = false
    self._disableCookies = true
  } else {
    var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
    var urihref = self.uri.href
    //fetch cookie in the Specified host
    if (targetCookieJar) {
      cookies = targetCookieJar.getCookieString(urihref)
    }
  }
 
  //if need cookie and cookie is not empty
  if (cookies && cookies.length) {
    if (self.originalCookieHeader) {
      // Don't overwrite existing Cookie header
      self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
    } else {
      self.setHeader('cookie', cookies)
    }
  }
  self._jar = jar
  return self
}
 
 
// Stream API
Request.prototype.pipe = function (dest, opts) {
  var self = this
 
  if (self.response) {
    if (self._destdata) {
      self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
    } else if (self._ended) {
      self.emit('error', new Error('You cannot pipe after the response has been ended.'))
    } else {
      stream.Stream.prototype.pipe.call(self, dest, opts)
      self.pipeDest(dest)
      return dest
    }
  } else {
    self.dests.push(dest)
    stream.Stream.prototype.pipe.call(self, dest, opts)
    return dest
  }
}
Request.prototype.write = function () {
  var self = this
  if (self._aborted) {return}
 
  if (!self._started) {
    self.start()
  }
  if (self.req) {
    return self.req.write.apply(self.req, arguments)
  }
}
Request.prototype.end = function (chunk) {
  var self = this
  if (self._aborted) {return}
 
  if (chunk) {
    self.write(chunk)
  }
  if (!self._started) {
    self.start()
  }
  if (self.req) {
    self.req.end()
  }
}
Request.prototype.pause = function () {
  var self = this
  if (!self.responseContent) {
    self._paused = true
  } else {
    self.responseContent.pause.apply(self.responseContent, arguments)
  }
}
Request.prototype.resume = function () {
  var self = this
  if (!self.responseContent) {
    self._paused = false
  } else {
    self.responseContent.resume.apply(self.responseContent, arguments)
  }
}
Request.prototype.destroy = function () {
  var self = this
  if (!self._ended) {
    self.end()
  } else if (self.response) {
    self.response.destroy()
  }
}
 
Request.defaultProxyHeaderWhiteList =
  Tunnel.defaultProxyHeaderWhiteList.slice()
 
Request.defaultProxyHeaderExclusiveList =
  Tunnel.defaultProxyHeaderExclusiveList.slice()
 
// Exports
 
Request.prototype.toJSON = requestToJSON
module.exports = Request
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/

Statements: 16.84% (97 / 576)      Branches: 0.25% (1 / 401)      Functions: 2.7% (2 / 74)      Lines: 16.96% (97 / 572)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/lib/
File Statements Branches Functions Lines
auth.js 10.71% (9 / 84) 0% (0 / 59) 0% (0 / 7) 10.84% (9 / 83)
cookies.js 50% (11 / 22) 0% (0 / 8) 33.33% (2 / 6) 50% (11 / 22)
getProxyFromURI.js 20% (5 / 25) 0% (0 / 31) 0% (0 / 5) 20% (5 / 25)
har.js 10.89% (11 / 101) 0% (0 / 84) 0% (0 / 10) 10.89% (11 / 101)
helpers.js 53.13% (17 / 32) 8.33% (1 / 12) 0% (0 / 8) 53.13% (17 / 32)
multipart.js 13.11% (8 / 61) 0% (0 / 38) 0% (0 / 9) 13.33% (8 / 60)
oauth.js 9.72% (7 / 72) 0% (0 / 57) 0% (0 / 7) 9.72% (7 / 72)
querystring.js 34.78% (8 / 23) 0% (0 / 20) 0% (0 / 6) 36.36% (8 / 22)
redirect.js 7.95% (7 / 88) 0% (0 / 66) 0% (0 / 5) 8.05% (7 / 87)
tunnel.js 20.59% (14 / 68) 0% (0 / 26) 0% (0 / 11) 20.59% (14 / 68)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/auth.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/auth.js

Statements: 10.71% (9 / 84)      Branches: 0% (0 / 59)      Functions: 0% (0 / 7)      Lines: 10.84% (9 / 83)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170    1       1       1                   1                               1                           1                                                                                                                                                       1                                 1                                               1    
'use strict'
 
var caseless = require('caseless')
  , uuid = require('uuid')
  , helpers = require('./helpers')
 
var md5 = helpers.md5
  , toBase64 = helpers.toBase64
 
 
function Auth (request) {
  // define all public properties here
  this.request = request
  this.hasAuth = false
  this.sentAuth = false
  this.bearerToken = null
  this.user = null
  this.pass = null
}
 
Auth.prototype.basic = function (user, pass, sendImmediately) {
  var self = this
  if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
    self.request.emit('error', new Error('auth() received invalid user or password'))
  }
  self.user = user
  self.pass = pass
  self.hasAuth = true
  var header = user + ':' + (pass || '')
  if (sendImmediately || typeof sendImmediately === 'undefined') {
    var authHeader = 'Basic ' + toBase64(header)
    self.sentAuth = true
    return authHeader
  }
}
 
Auth.prototype.bearer = function (bearer, sendImmediately) {
  var self = this
  self.bearerToken = bearer
  self.hasAuth = true
  if (sendImmediately || typeof sendImmediately === 'undefined') {
    if (typeof bearer === 'function') {
      bearer = bearer()
    }
    var authHeader = 'Bearer ' + (bearer || '')
    self.sentAuth = true
    return authHeader
  }
}
 
Auth.prototype.digest = function (method, path, authHeader) {
  // TODO: More complete implementation of RFC 2617.
  //   - handle challenge.domain
  //   - support qop="auth-int" only
  //   - handle Authentication-Info (not necessarily?)
  //   - check challenge.stale (not necessarily?)
  //   - increase nc (not necessarily?)
  // For reference:
  // http://tools.ietf.org/html/rfc2617#section-3
  // https://github.com/bagder/curl/blob/master/lib/http_digest.c
 
  var self = this
 
  var challenge = {}
  var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
  for (;;) {
    var match = re.exec(authHeader)
    if (!match) {
      break
    }
    challenge[match[1]] = match[2] || match[3]
  }
 
  /**
   * RFC 2617: handle both MD5 and MD5-sess algorithms.
   *
   * If the algorithm directive's value is "MD5" or unspecified, then HA1 is
   *   HA1=MD5(username:realm:password)
   * If the algorithm directive's value is "MD5-sess", then HA1 is
   *   HA1=MD5(MD5(username:realm:password):nonce:cnonce)
   */
  var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
    var ha1 = md5(user + ':' + realm + ':' + pass)
    if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
      return md5(ha1 + ':' + nonce + ':' + cnonce)
    } else {
      return ha1
    }
  }
 
  var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
  var nc = qop && '00000001'
  var cnonce = qop && uuid().replace(/-/g, '')
  var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce)
  var ha2 = md5(method + ':' + path)
  var digestResponse = qop
    ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
    : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
  var authValues = {
    username: self.user,
    realm: challenge.realm,
    nonce: challenge.nonce,
    uri: path,
    qop: qop,
    response: digestResponse,
    nc: nc,
    cnonce: cnonce,
    algorithm: challenge.algorithm,
    opaque: challenge.opaque
  }
 
  authHeader = []
  for (var k in authValues) {
    if (authValues[k]) {
      if (k === 'qop' || k === 'nc' || k === 'algorithm') {
        authHeader.push(k + '=' + authValues[k])
      } else {
        authHeader.push(k + '="' + authValues[k] + '"')
      }
    }
  }
  authHeader = 'Digest ' + authHeader.join(', ')
  self.sentAuth = true
  return authHeader
}
 
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
  var self = this
    , request = self.request
 
  var authHeader
  if (bearer === undefined && user === undefined) {
    self.request.emit('error', new Error('no auth mechanism defined'))
  } else if (bearer !== undefined) {
    authHeader = self.bearer(bearer, sendImmediately)
  } else {
    authHeader = self.basic(user, pass, sendImmediately)
  }
  if (authHeader) {
    request.setHeader('authorization', authHeader)
  }
}
 
Auth.prototype.onResponse = function (response) {
  var self = this
    , request = self.request
 
  if (!self.hasAuth || self.sentAuth) { return null }
 
  var c = caseless(response.headers)
 
  var authHeader = c.get('www-authenticate')
  var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
  request.debug('reauth', authVerb)
 
  switch (authVerb) {
    case 'basic':
      return self.basic(self.user, self.pass, true)
 
    case 'bearer':
      return self.bearer(self.bearerToken, true)
 
    case 'digest':
      return self.digest(request.method, request.path, authHeader)
  }
}
 
exports.Auth = Auth
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/cookies.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/cookies.js

Statements: 50% (11 / 22)      Branches: 0% (0 / 8)      Functions: 33.33% (2 / 6)      Lines: 50% (11 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41    1   1       1                     1 1 1   1       1       1         1 1      
'use strict'
 
var tough = require('tough-cookie')
 
var Cookie = tough.Cookie
  , CookieJar = tough.CookieJar
 
 
exports.parse = function(str) {
  if (str && str.uri) {
    str = str.uri
  }
  if (typeof str !== 'string') {
    throw new Error('The cookie function only accepts STRING as param')
  }
  return Cookie.parse(str, {loose: true})
}
 
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
function RequestJar(store) {
  var self = this
  self._jar = new CookieJar(store, {looseMode: true})
}
RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
  var self = this
  return self._jar.setCookieSync(cookieOrStr, uri, options || {})
}
RequestJar.prototype.getCookieString = function(uri) {
  var self = this
  return self._jar.getCookieStringSync(uri)
}
RequestJar.prototype.getCookies = function(uri) {
  var self = this
  return self._jar.getCookiesSync(uri)
}
 
exports.jar = function(store) {
  return new RequestJar(store)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/getProxyFromURI.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/getProxyFromURI.js

Statements: 20% (5 / 25)      Branches: 0% (0 / 31)      Functions: 0% (0 / 5)      Lines: 20% (5 / 25)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81    1         1                     1                                         1                                                                             1    
'use strict'
 
function formatHostname(hostname) {
  // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
  return hostname.replace(/^\.*/, '.').toLowerCase()
}
 
function parseNoProxyZone(zone) {
  zone = zone.trim().toLowerCase()
 
  var zoneParts = zone.split(':', 2)
    , zoneHost = formatHostname(zoneParts[0])
    , zonePort = zoneParts[1]
    , hasPort = zone.indexOf(':') > -1
 
  return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
}
 
function uriInNoProxy(uri, noProxy) {
  var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
    , hostname = formatHostname(uri.hostname)
    , noProxyList = noProxy.split(',')
 
  // iterate through the noProxyList until it finds a match.
  return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
    var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
      , hostnameMatched = (
          isMatchedAt > -1 &&
          (isMatchedAt === hostname.length - noProxyZone.hostname.length)
        )
 
    if (noProxyZone.hasPort) {
      return (port === noProxyZone.port) && hostnameMatched
    }
 
    return hostnameMatched
  })
}
 
function getProxyFromURI(uri) {
  // Decide the proper request proxy to use based on the request URI object and the
  // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
  // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
 
  var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
 
  // if the noProxy is a wildcard then return null
 
  if (noProxy === '*') {
    return null
  }
 
  // if the noProxy is not empty and the uri is found return null
 
  if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
    return null
  }
 
  // Check for HTTP or HTTPS Proxy in environment Else default to null
 
  if (uri.protocol === 'http:') {
    return process.env.HTTP_PROXY ||
           process.env.http_proxy || null
  }
 
  if (uri.protocol === 'https:') {
    return process.env.HTTPS_PROXY ||
           process.env.https_proxy ||
           process.env.HTTP_PROXY  ||
           process.env.http_proxy  || null
  }
 
  // if none of that works, return null
  // (What uri protocol are you using then?)
 
  return null
}
 
module.exports = getProxyFromURI
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/har.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/har.js

Statements: 10.89% (11 / 101)      Branches: 0% (0 / 84)      Functions: 0% (0 / 10)      Lines: 10.89% (11 / 101)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217    1 1 1 1   1       1                                   1                                                                 1                                                                                                       1                                                                                                     1                                                                                                 1    
'use strict'
 
var fs = require('fs')
var qs = require('querystring')
var validate = require('har-validator')
var extend = require('extend')
 
function Har (request) {
  this.request = request
}
 
Har.prototype.reducer = function (obj, pair) {
  // new property ?
  if (obj[pair.name] === undefined) {
    obj[pair.name] = pair.value
    return obj
  }
 
  // existing? convert to array
  var arr = [
    obj[pair.name],
    pair.value
  ]
 
  obj[pair.name] = arr
 
  return obj
}
 
Har.prototype.prep = function (data) {
  // construct utility properties
  data.queryObj = {}
  data.headersObj = {}
  data.postData.jsonObj = false
  data.postData.paramsObj = false
 
  // construct query objects
  if (data.queryString && data.queryString.length) {
    data.queryObj = data.queryString.reduce(this.reducer, {})
  }
 
  // construct headers objects
  if (data.headers && data.headers.length) {
    // loweCase header keys
    data.headersObj = data.headers.reduceRight(function (headers, header) {
      headers[header.name] = header.value
      return headers
    }, {})
  }
 
  // construct Cookie header
  if (data.cookies && data.cookies.length) {
    var cookies = data.cookies.map(function (cookie) {
      return cookie.name + '=' + cookie.value
    })
 
    if (cookies.length) {
      data.headersObj.cookie = cookies.join('; ')
    }
  }
 
  // prep body
  function some (arr) {
    return arr.some(function (type) {
      return data.postData.mimeType.indexOf(type) === 0
    })
  }
 
  if (some([
    'multipart/mixed',
    'multipart/related',
    'multipart/form-data',
    'multipart/alternative'])) {
 
    // reset values
    data.postData.mimeType = 'multipart/form-data'
  }
 
  else if (some([
    'application/x-www-form-urlencoded'])) {
 
    if (!data.postData.params) {
      data.postData.text = ''
    } else {
      data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
 
      // always overwrite
      data.postData.text = qs.stringify(data.postData.paramsObj)
    }
  }
 
  else if (some([
    'text/json',
    'text/x-json',
    'application/json',
    'application/x-json'])) {
 
    data.postData.mimeType = 'application/json'
 
    if (data.postData.text) {
      try {
        data.postData.jsonObj = JSON.parse(data.postData.text)
      } catch (e) {
        this.request.debug(e)
 
        // force back to text/plain
        data.postData.mimeType = 'text/plain'
      }
    }
  }
 
  return data
}
 
Har.prototype.options = function (options) {
  // skip if no har property defined
  if (!options.har) {
    return options
  }
 
  var har = {}
  extend(har, options.har)
 
  // only process the first entry
  if (har.log && har.log.entries) {
    har = har.log.entries[0]
  }
 
  // add optional properties to make validation successful
  har.url = har.url || options.url || options.uri || options.baseUrl || '/'
  har.httpVersion = har.httpVersion || 'HTTP/1.1'
  har.queryString = har.queryString || []
  har.headers = har.headers || []
  har.cookies = har.cookies || []
  har.postData = har.postData || {}
  har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
 
  har.bodySize = 0
  har.headersSize = 0
  har.postData.size = 0
 
  if (!validate.request(har)) {
    return options
  }
 
  // clean up and get some utility properties
  var req = this.prep(har)
 
  // construct new options
  if (req.url) {
    options.url = req.url
  }
 
  if (req.method) {
    options.method = req.method
  }
 
  if (Object.keys(req.queryObj).length) {
    options.qs = req.queryObj
  }
 
  if (Object.keys(req.headersObj).length) {
    options.headers = req.headersObj
  }
 
  function test (type) {
    return req.postData.mimeType.indexOf(type) === 0
  }
  if (test('application/x-www-form-urlencoded')) {
    options.form = req.postData.paramsObj
  }
  else if (test('application/json')) {
    if (req.postData.jsonObj) {
      options.body = req.postData.jsonObj
      options.json = true
    }
  }
  else if (test('multipart/form-data')) {
    options.formData = {}
 
    req.postData.params.forEach(function (param) {
      var attachment = {}
 
      if (!param.fileName && !param.fileName && !param.contentType) {
        options.formData[param.name] = param.value
        return
      }
 
      // attempt to read from disk!
      if (param.fileName && !param.value) {
        attachment.value = fs.createReadStream(param.fileName)
      } else if (param.value) {
        attachment.value = param.value
      }
 
      if (param.fileName) {
        attachment.options = {
          filename: param.fileName,
          contentType: param.contentType ? param.contentType : null
        }
      }
 
      options.formData[param.name] = attachment
    })
  }
  else {
    if (req.postData.text) {
      options.body = req.postData.text
    }
  }
 
  return options
}
 
exports.Har = Har
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/helpers.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/helpers.js

Statements: 53.13% (17 / 32)      Branches: 8.33% (1 / 12)      Functions: 0% (0 / 8)      Lines: 53.13% (17 / 32)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68    1       1       1                 1                   1       1       1       1               1                 1 1 1 1 1 1 1 1    
'use strict'
 
var jsonSafeStringify = require('json-stringify-safe')
  , crypto = require('crypto')
  , Buffer = require('safe-buffer').Buffer
 
var defer = typeof setImmediate === 'undefined'
  ? process.nextTick
  : setImmediate
 
function paramsHaveRequestBody(params) {
  return (
    params.body ||
    params.requestBodyStream ||
    (params.json && typeof params.json !== 'boolean') ||
    params.multipart
  )
}
 
function safeStringify (obj, replacer) {
  var ret
  try {
    ret = JSON.stringify(obj, replacer)
  } catch (e) {
    ret = jsonSafeStringify(obj, replacer)
  }
  return ret
}
 
function md5 (str) {
  return crypto.createHash('md5').update(str).digest('hex')
}
 
function isReadStream (rs) {
  return rs.readable && rs.path && rs.mode
}
 
function toBase64 (str) {
  return Buffer.from(str || '', 'utf8').toString('base64')
}
 
function copy (obj) {
  var o = {}
  Object.keys(obj).forEach(function (i) {
    o[i] = obj[i]
  })
  return o
}
 
function version () {
  var numbers = process.version.replace('v', '').split('.')
  return {
    major: parseInt(numbers[0], 10),
    minor: parseInt(numbers[1], 10),
    patch: parseInt(numbers[2], 10)
  }
}
 
exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify         = safeStringify
exports.md5                   = md5
exports.isReadStream          = isReadStream
exports.toBase64              = toBase64
exports.copy                  = copy
exports.version               = version
exports.defer                 = defer
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/multipart.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/multipart.js

Statements: 13.11% (8 / 61)      Branches: 0% (0 / 38)      Functions: 0% (0 / 9)      Lines: 13.33% (8 / 60)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115    1           1             1                                                             1                                       1       1                                                             1                     1    
'use strict'
 
var uuid = require('uuid')
  , CombinedStream = require('combined-stream')
  , isstream = require('isstream')
  , Buffer = require('safe-buffer').Buffer
 
 
function Multipart (request) {
  this.request = request
  this.boundary = uuid()
  this.chunked = false
  this.body = null
}
 
Multipart.prototype.isChunked = function (options) {
  var self = this
    , chunked = false
    , parts = options.data || options
 
  if (!parts.forEach) {
    self.request.emit('error', new Error('Argument error, options.multipart.'))
  }
 
  if (options.chunked !== undefined) {
    chunked = options.chunked
  }
 
  if (self.request.getHeader('transfer-encoding') === 'chunked') {
    chunked = true
  }
 
  if (!chunked) {
    parts.forEach(function (part) {
      if (typeof part.body === 'undefined') {
        self.request.emit('error', new Error('Body attribute missing in multipart.'))
      }
      if (isstream(part.body)) {
        chunked = true
      }
    })
  }
 
  return chunked
}
 
Multipart.prototype.setHeaders = function (chunked) {
  var self = this
 
  if (chunked && !self.request.hasHeader('transfer-encoding')) {
    self.request.setHeader('transfer-encoding', 'chunked')
  }
 
  var header = self.request.getHeader('content-type')
 
  if (!header || header.indexOf('multipart') === -1) {
    self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
  } else {
    if (header.indexOf('boundary') !== -1) {
      self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
    } else {
      self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
    }
  }
}
 
Multipart.prototype.build = function (parts, chunked) {
  var self = this
  var body = chunked ? new CombinedStream() : []
 
  function add (part) {
    if (typeof part === 'number') {
      part = part.toString()
    }
    return chunked ? body.append(part) : body.push(Buffer.from(part))
  }
 
  if (self.request.preambleCRLF) {
    add('\r\n')
  }
 
  parts.forEach(function (part) {
    var preamble = '--' + self.boundary + '\r\n'
    Object.keys(part).forEach(function (key) {
      if (key === 'body') { return }
      preamble += key + ': ' + part[key] + '\r\n'
    })
    preamble += '\r\n'
    add(preamble)
    add(part.body)
    add('\r\n')
  })
  add('--' + self.boundary + '--')
 
  if (self.request.postambleCRLF) {
    add('\r\n')
  }
 
  return body
}
 
Multipart.prototype.onRequest = function (options) {
  var self = this
 
  var chunked = self.isChunked(options)
    , parts = options.data || options
 
  self.setHeaders(chunked)
  self.chunked = chunked
  self.body = self.build(parts, chunked)
}
 
exports.Multipart = Multipart
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/oauth.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/oauth.js

Statements: 9.72% (7 / 72)      Branches: 0% (0 / 57)      Functions: 0% (0 / 7)      Lines: 9.72% (7 / 72)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150    1                 1         1                                                                                             1                         1                                 1                                                                                                           1    
'use strict'
 
var url = require('url')
  , qs = require('qs')
  , caseless = require('caseless')
  , uuid = require('uuid')
  , oauth = require('oauth-sign')
  , crypto = require('crypto')
  , Buffer = require('safe-buffer').Buffer
 
 
function OAuth (request) {
  this.request = request
  this.params = null
}
 
OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
  var oa = {}
  for (var i in _oauth) {
    oa['oauth_' + i] = _oauth[i]
  }
  if (!oa.oauth_version) {
    oa.oauth_version = '1.0'
  }
  if (!oa.oauth_timestamp) {
    oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
  }
  if (!oa.oauth_nonce) {
    oa.oauth_nonce = uuid().replace(/-/g, '')
  }
  if (!oa.oauth_signature_method) {
    oa.oauth_signature_method = 'HMAC-SHA1'
  }
 
  var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
  delete oa.oauth_consumer_secret
  delete oa.oauth_private_key
 
  var token_secret = oa.oauth_token_secret
  delete oa.oauth_token_secret
 
  var realm = oa.oauth_realm
  delete oa.oauth_realm
  delete oa.oauth_transport_method
 
  var baseurl = uri.protocol + '//' + uri.host + uri.pathname
  var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
 
  oa.oauth_signature = oauth.sign(
    oa.oauth_signature_method,
    method,
    baseurl,
    params,
    consumer_secret_or_private_key,
    token_secret)
 
  if (realm) {
    oa.realm = realm
  }
 
  return oa
}
 
OAuth.prototype.buildBodyHash = function(_oauth, body) {
  if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
    this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
      ' signature_method not supported with body_hash signing.'))
  }
 
  var shasum = crypto.createHash('sha1')
  shasum.update(body || '')
  var sha1 = shasum.digest('hex')
 
  return Buffer.from(sha1).toString('base64')
}
 
OAuth.prototype.concatParams = function (oa, sep, wrap) {
  wrap = wrap || ''
 
  var params = Object.keys(oa).filter(function (i) {
    return i !== 'realm' && i !== 'oauth_signature'
  }).sort()
 
  if (oa.realm) {
    params.splice(0, 0, 'realm')
  }
  params.push('oauth_signature')
 
  return params.map(function (i) {
    return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
  }).join(sep)
}
 
OAuth.prototype.onRequest = function (_oauth) {
  var self = this
  self.params = _oauth
 
  var uri = self.request.uri || {}
    , method = self.request.method || ''
    , headers = caseless(self.request.headers)
    , body = self.request.body || ''
    , qsLib = self.request.qsLib || qs
 
  var form
    , query
    , contentType = headers.get('content-type') || ''
    , formContentType = 'application/x-www-form-urlencoded'
    , transport = _oauth.transport_method || 'header'
 
  if (contentType.slice(0, formContentType.length) === formContentType) {
    contentType = formContentType
    form = body
  }
  if (uri.query) {
    query = uri.query
  }
  if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
    self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
      'and content-type ' + formContentType))
  }
 
  if (!form && typeof _oauth.body_hash === 'boolean') {
    _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString())
  }
 
  var oa = self.buildParams(_oauth, uri, method, query, form, qsLib)
 
  switch (transport) {
    case 'header':
      self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'))
      break
 
    case 'query':
      var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&')
      self.request.uri = url.parse(href)
      self.request.path = self.request.uri.path
      break
 
    case 'body':
      self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&')
      break
 
    default:
      self.request.emit('error', new Error('oauth: transport_method invalid'))
  }
}
 
exports.OAuth = OAuth
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/querystring.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/querystring.js

Statements: 34.78% (8 / 23)      Branches: 0% (0 / 20)      Functions: 0% (0 / 6)      Lines: 36.36% (8 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53    1       1               1                   1                 1                 1           1   1    
'use strict'
 
var qs = require('qs')
  , querystring = require('querystring')
 
 
function Querystring (request) {
  this.request = request
  this.lib = null
  this.useQuerystring = null
  this.parseOptions = null
  this.stringifyOptions = null
}
 
Querystring.prototype.init = function (options) {
  if (this.lib) {return}
 
  this.useQuerystring = options.useQuerystring
  this.lib = (this.useQuerystring ? querystring : qs)
 
  this.parseOptions = options.qsParseOptions || {}
  this.stringifyOptions = options.qsStringifyOptions || {}
}
 
Querystring.prototype.stringify = function (obj) {
  return (this.useQuerystring)
    ? this.rfc3986(this.lib.stringify(obj,
      this.stringifyOptions.sep || null,
      this.stringifyOptions.eq || null,
      this.stringifyOptions))
    : this.lib.stringify(obj, this.stringifyOptions)
}
 
Querystring.prototype.parse = function (str) {
  return (this.useQuerystring)
    ? this.lib.parse(str,
      this.parseOptions.sep || null,
      this.parseOptions.eq || null,
      this.parseOptions)
    : this.lib.parse(str, this.parseOptions)
}
 
Querystring.prototype.rfc3986 = function (str) {
  return str.replace(/[!'()*]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  })
}
 
Querystring.prototype.unescape = querystring.unescape
 
exports.Querystring = Querystring
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/redirect.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/redirect.js

Statements: 7.95% (7 / 88)      Branches: 0% (0 / 66)      Functions: 0% (0 / 5)      Lines: 8.05% (7 / 87)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159    1 1   1                         1                                                   1                                                                   1                                                                                                                                                           1    
'use strict'
 
var url = require('url')
var isUrl = /^https?:/
 
function Redirect (request) {
  this.request = request
  this.followRedirect = true
  this.followRedirects = true
  this.followAllRedirects = false
  this.followOriginalHttpMethod = false
  this.allowRedirect = function () {return true}
  this.maxRedirects = 10
  this.redirects = []
  this.redirectsFollowed = 0
  this.removeRefererHeader = false
}
 
Redirect.prototype.onRequest = function (options) {
  var self = this
 
  if (options.maxRedirects !== undefined) {
    self.maxRedirects = options.maxRedirects
  }
  if (typeof options.followRedirect === 'function') {
    self.allowRedirect = options.followRedirect
  }
  if (options.followRedirect !== undefined) {
    self.followRedirects = !!options.followRedirect
  }
  if (options.followAllRedirects !== undefined) {
    self.followAllRedirects = options.followAllRedirects
  }
  if (self.followRedirects || self.followAllRedirects) {
    self.redirects = self.redirects || []
  }
  if (options.removeRefererHeader !== undefined) {
    self.removeRefererHeader = options.removeRefererHeader
  }
  if (options.followOriginalHttpMethod !== undefined) {
    self.followOriginalHttpMethod = options.followOriginalHttpMethod
  }
}
 
Redirect.prototype.redirectTo = function (response) {
  var self = this
    , request = self.request
 
  var redirectTo = null
  if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
    var location = response.caseless.get('location')
    request.debug('redirect', location)
 
    if (self.followAllRedirects) {
      redirectTo = location
    } else if (self.followRedirects) {
      switch (request.method) {
        case 'PATCH':
        case 'PUT':
        case 'POST':
        case 'DELETE':
          // Do not follow redirects
          break
        default:
          redirectTo = location
          break
      }
    }
  } else if (response.statusCode === 401) {
    var authHeader = request._auth.onResponse(response)
    if (authHeader) {
      request.setHeader('authorization', authHeader)
      redirectTo = request.uri
    }
  }
  return redirectTo
}
 
Redirect.prototype.onResponse = function (response) {
  var self = this
    , request = self.request
 
  var redirectTo = self.redirectTo(response)
  if (!redirectTo || !self.allowRedirect.call(request, response)) {
    return false
  }
 
  request.debug('redirect to', redirectTo)
 
  // ignore any potential response body.  it cannot possibly be useful
  // to us at this point.
  // response.resume should be defined, but check anyway before calling. Workaround for browserify.
  if (response.resume) {
    response.resume()
  }
 
  if (self.redirectsFollowed >= self.maxRedirects) {
    request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
    return false
  }
  self.redirectsFollowed += 1
 
  if (!isUrl.test(redirectTo)) {
    redirectTo = url.resolve(request.uri.href, redirectTo)
  }
 
  var uriPrev = request.uri
  request.uri = url.parse(redirectTo)
 
  // handle the case where we change protocol from https to http or vice versa
  if (request.uri.protocol !== uriPrev.protocol) {
    delete request.agent
  }
 
  self.redirects.push(
    { statusCode : response.statusCode
    , redirectUri: redirectTo
    }
  )
  if (self.followAllRedirects && request.method !== 'HEAD'
    && response.statusCode !== 401 && response.statusCode !== 307) {
    request.method = self.followOriginalHttpMethod ? request.method : 'GET'
  }
  // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
  delete request.src
  delete request.req
  delete request._started
  if (response.statusCode !== 401 && response.statusCode !== 307) {
    // Remove parameters from the previous response, unless this is the second request
    // for a server that requires digest authentication.
    delete request.body
    delete request._form
    if (request.headers) {
      request.removeHeader('host')
      request.removeHeader('content-type')
      request.removeHeader('content-length')
      if (request.uri.hostname !== request.originalHost.split(':')[0]) {
        // Remove authorization if changing hostnames (but not if just
        // changing ports or protocols).  This matches the behavior of curl:
        // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
        request.removeHeader('authorization')
      }
    }
  }
 
  if (!self.removeRefererHeader) {
    request.setHeader('referer', uriPrev.href)
  }
 
  request.emit('redirect')
 
  request.init()
 
  return true
}
 
exports.Redirect = Redirect
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/tunnel.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/lib/tunnel.js

Statements: 20.59% (14 / 68)      Branches: 0% (0 / 26)      Functions: 0% (0 / 11)      Lines: 20.59% (14 / 68)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178    1     1                                               1       1                               1                                 1                                                 1           1               1                 1                                     1                                                                               1 1 1    
'use strict'
 
var url = require('url')
  , tunnel = require('tunnel-agent')
 
var defaultProxyHeaderWhiteList = [
  'accept',
  'accept-charset',
  'accept-encoding',
  'accept-language',
  'accept-ranges',
  'cache-control',
  'content-encoding',
  'content-language',
  'content-location',
  'content-md5',
  'content-range',
  'content-type',
  'connection',
  'date',
  'expect',
  'max-forwards',
  'pragma',
  'referer',
  'te',
  'user-agent',
  'via'
]
 
var defaultProxyHeaderExclusiveList = [
  'proxy-authorization'
]
 
function constructProxyHost(uriObject) {
  var port = uriObject.port
    , protocol = uriObject.protocol
    , proxyHost = uriObject.hostname + ':'
 
  if (port) {
    proxyHost += port
  } else if (protocol === 'https:') {
    proxyHost += '443'
  } else {
    proxyHost += '80'
  }
 
  return proxyHost
}
 
function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
  var whiteList = proxyHeaderWhiteList
    .reduce(function (set, header) {
      set[header.toLowerCase()] = true
      return set
    }, {})
 
  return Object.keys(headers)
    .filter(function (header) {
      return whiteList[header.toLowerCase()]
    })
    .reduce(function (set, header) {
      set[header] = headers[header]
      return set
    }, {})
}
 
function constructTunnelOptions (request, proxyHeaders) {
  var proxy = request.proxy
 
  var tunnelOptions = {
    proxy : {
      host      : proxy.hostname,
      port      : +proxy.port,
      proxyAuth : proxy.auth,
      headers   : proxyHeaders
    },
    headers            : request.headers,
    ca                 : request.ca,
    cert               : request.cert,
    key                : request.key,
    passphrase         : request.passphrase,
    pfx                : request.pfx,
    ciphers            : request.ciphers,
    rejectUnauthorized : request.rejectUnauthorized,
    secureOptions      : request.secureOptions,
    secureProtocol     : request.secureProtocol
  }
 
  return tunnelOptions
}
 
function constructTunnelFnName(uri, proxy) {
  var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
  var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
  return [uriProtocol, proxyProtocol].join('Over')
}
 
function getTunnelFn(request) {
  var uri = request.uri
  var proxy = request.proxy
  var tunnelFnName = constructTunnelFnName(uri, proxy)
  return tunnel[tunnelFnName]
}
 
 
function Tunnel (request) {
  this.request = request
  this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
  this.proxyHeaderExclusiveList = []
  if (typeof request.tunnel !== 'undefined') {
    this.tunnelOverride = request.tunnel
  }
}
 
Tunnel.prototype.isEnabled = function () {
  var self = this
    , request = self.request
  // Tunnel HTTPS by default. Allow the user to override this setting.
 
  // If self.tunnelOverride is set (the user specified a value), use it.
  if (typeof self.tunnelOverride !== 'undefined') {
    return self.tunnelOverride
  }
 
  // If the destination is HTTPS, tunnel.
  if (request.uri.protocol === 'https:') {
    return true
  }
 
  // Otherwise, do not use tunnel.
  return false
}
 
Tunnel.prototype.setup = function (options) {
  var self = this
    , request = self.request
 
  options = options || {}
 
  if (typeof request.proxy === 'string') {
    request.proxy = url.parse(request.proxy)
  }
 
  if (!request.proxy || !request.tunnel) {
    return false
  }
 
  // Setup Proxy Header Exclusive List and White List
  if (options.proxyHeaderWhiteList) {
    self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
  }
  if (options.proxyHeaderExclusiveList) {
    self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
  }
 
  var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
  var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
 
  // Setup Proxy Headers and Proxy Headers Host
  // Only send the Proxy White Listed Header names
  var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
  proxyHeaders.host = constructProxyHost(request.uri)
 
  proxyHeaderExclusiveList.forEach(request.removeHeader, request)
 
  // Set Agent from Tunnel Data
  var tunnelFn = getTunnelFn(request)
  var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
  request.agent = tunnelFn(tunnelOptions)
 
  return true
}
 
Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
exports.Tunnel = Tunnel
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws-sign2/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws-sign2/

Statements: 42.22% (19 / 45)      Branches: 0% (0 / 14)      Functions: 0% (0 / 9)      Lines: 45.24% (19 / 42)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws-sign2/
File Statements Branches Functions Lines
index.js 42.22% (19 / 45) 0% (0 / 14) 0% (0 / 9) 45.24% (19 / 42)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws-sign2/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws-sign2/index.js

Statements: 42.22% (19 / 45)      Branches: 0% (0 / 14)      Functions: 0% (0 / 9)      Lines: 45.24% (19 / 42)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                          1               1                                                   1       1 1                   1       1                   1       1                       1       1                                     1                       1                               1     1                               1                           1                         1                           1    
 
/*!
 *  Copyright 2010 LearnBoost <dev@learnboost.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/**
 * Module dependencies.
 */
 
var crypto = require('crypto')
  , parse = require('url').parse
  ;
 
/**
 * Valid keys.
 */
 
var keys = 
  [ 'acl'
  , 'location'
  , 'logging'
  , 'notification'
  , 'partNumber'
  , 'policy'
  , 'requestPayment'
  , 'torrent'
  , 'uploadId'
  , 'uploads'
  , 'versionId'
  , 'versioning'
  , 'versions'
  , 'website'
  ]
 
/**
 * Return an "Authorization" header value with the given `options`
 * in the form of "AWS <key>:<signature>"
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function authorization (options) {
  return 'AWS ' + options.key + ':' + sign(options)
}
 
module.exports = authorization
module.exports.authorization = authorization
 
/**
 * Simple HMAC-SHA1 Wrapper
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */ 
 
function hmacSha1 (options) {
  return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
}
 
module.exports.hmacSha1 = hmacSha1
 
/**
 * Create a base64 sha1 HMAC for `options`. 
 * 
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function sign (options) {
  options.message = stringToSign(options)
  return hmacSha1(options)
}
module.exports.sign = sign
 
/**
 * Create a base64 sha1 HMAC for `options`. 
 *
 * Specifically to be used with S3 presigned URLs
 * 
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function signQuery (options) {
  options.message = queryStringToSign(options)
  return hmacSha1(options)
}
module.exports.signQuery= signQuery
 
/**
 * Return a string for sign() with the given `options`.
 *
 * Spec:
 * 
 *    <verb>\n
 *    <md5>\n
 *    <content-type>\n
 *    <date>\n
 *    [headers\n]
 *    <resource>
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function stringToSign (options) {
  var headers = options.amazonHeaders || ''
  if (headers) headers += '\n'
  var r = 
    [ options.verb
    , options.md5
    , options.contentType
    , options.date ? options.date.toUTCString() : ''
    , headers + options.resource
    ]
  return r.join('\n')
}
module.exports.queryStringToSign = stringToSign
 
/**
 * Return a string for sign() with the given `options`, but is meant exclusively
 * for S3 presigned URLs
 *
 * Spec:
 * 
 *    <date>\n
 *    <resource>
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function queryStringToSign (options){
  return 'GET\n\n\n' + options.date + '\n' + options.resource
}
module.exports.queryStringToSign = queryStringToSign
 
/**
 * Perform the following:
 *
 *  - ignore non-amazon headers
 *  - lowercase fields
 *  - sort lexicographically
 *  - trim whitespace between ":"
 *  - join with newline
 *
 * @param {Object} headers
 * @return {String}
 * @api private
 */
 
function canonicalizeHeaders (headers) {
  var buf = []
    , fields = Object.keys(headers)
    ;
  for (var i = 0, len = fields.length; i < len; ++i) {
    var field = fields[i]
      , val = headers[field]
      , field = field.toLowerCase()
      ;
    if (0 !== field.indexOf('x-amz')) continue
    buf.push(field + ':' + val)
  }
  return buf.sort().join('\n')
}
module.exports.canonicalizeHeaders = canonicalizeHeaders
 
/**
 * Perform the following:
 *
 *  - ignore non sub-resources
 *  - sort lexicographically
 *
 * @param {String} resource
 * @return {String}
 * @api private
 */
 
function canonicalizeResource (resource) {
  var url = parse(resource, true)
    , path = url.pathname
    , buf = []
    ;
 
  Object.keys(url.query).forEach(function(key){
    if (!~keys.indexOf(key)) return
    var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
    buf.push(key + val)
  })
 
  return path + (buf.length ? '?' + buf.sort().join('&') : '')
}
module.exports.canonicalizeResource = canonicalizeResource
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/

Statements: 18.18% (42 / 231)      Branches: 0% (0 / 197)      Functions: 7.32% (3 / 41)      Lines: 19.63% (42 / 214)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/
File Statements Branches Functions Lines
aws4.js 15.24% (25 / 164) 0% (0 / 173) 0% (0 / 30) 16.56% (25 / 151)
lru.js 25.37% (17 / 67) 0% (0 / 24) 27.27% (3 / 11) 26.98% (17 / 63)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/aws4.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/aws4.js

Statements: 15.24% (25 / 164)      Branches: 0% (0 / 173)      Functions: 0% (0 / 30)      Lines: 16.56% (25 / 151)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 3341                 1       1         1               1                                                               1                           1               1             1                                                                                                   1                           1                         1       1               1                           1                 1                                                                                                             1   1                 1             1                 1                 1                                                 1                       1   1        
var aws4 = exports,
    url = require('url'),
    querystring = require('querystring'),
    crypto = require('crypto'),
    lru = require('./lru'),
    credentialsCache = lru(1000)
 
// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
 
function hmac(key, string, encoding) {
  return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
}
 
function hash(string, encoding) {
  return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
}
 
// This function assumes the string has already been percent encoded
function encodeRfc3986(urlEncodedString) {
  return urlEncodedString.replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  })
}
 
// request: { path | body, [host], [method], [headers], [service], [region] }
// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
function RequestSigner(request, credentials) {
 
  if (typeof request === 'string') request = url.parse(request)
 
  var headers = request.headers = (request.headers || {}),
      hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
 
  this.request = request
  this.credentials = credentials || this.defaultCredentials()
 
  this.service = request.service || hostParts[0] || ''
  this.region = request.region || hostParts[1] || 'us-east-1'
 
  // SES uses a different domain from the service name
  if (this.service === 'email') this.service = 'ses'
 
  if (!request.method && request.body)
    request.method = 'POST'
 
  if (!headers.Host && !headers.host) {
    headers.Host = request.hostname || request.host || this.createHost()
 
    // If a port is specified explicitly, use it as is
    if (request.port)
      headers.Host += ':' + request.port
  }
  if (!request.hostname && !request.host)
    request.hostname = headers.Host || headers.host
 
  this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
}
 
RequestSigner.prototype.matchHost = function(host) {
  var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
  var hostParts = (match || []).slice(1, 3)
 
  // ES's hostParts are sometimes the other way round, if the value that is expected
  // to be region equals ‘es’ switch them back
  // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
  if (hostParts[1] === 'es')
    hostParts = hostParts.reverse()
 
  return hostParts
}
 
// http://docs.aws.amazon.com/general/latest/gr/rande.html
RequestSigner.prototype.isSingleRegion = function() {
  // Special case for S3 and SimpleDB in us-east-1
  if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
 
  return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
    .indexOf(this.service) >= 0
}
 
RequestSigner.prototype.createHost = function() {
  var region = this.isSingleRegion() ? '' :
        (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
      service = this.service === 'ses' ? 'email' : this.service
  return service + region + '.amazonaws.com'
}
 
RequestSigner.prototype.prepareRequest = function() {
  this.parsePath()
 
  var request = this.request, headers = request.headers, query
 
  if (request.signQuery) {
 
    this.parsedPath.query = query = this.parsedPath.query || {}
 
    if (this.credentials.sessionToken)
      query['X-Amz-Security-Token'] = this.credentials.sessionToken
 
    if (this.service === 's3' && !query['X-Amz-Expires'])
      query['X-Amz-Expires'] = 86400
 
    if (query['X-Amz-Date'])
      this.datetime = query['X-Amz-Date']
    else
      query['X-Amz-Date'] = this.getDateTime()
 
    query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
    query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
    query['X-Amz-SignedHeaders'] = this.signedHeaders()
 
  } else {
 
    if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
      if (request.body && !headers['Content-Type'] && !headers['content-type'])
        headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
 
      if (request.body && !headers['Content-Length'] && !headers['content-length'])
        headers['Content-Length'] = Buffer.byteLength(request.body)
 
      if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
        headers['X-Amz-Security-Token'] = this.credentials.sessionToken
 
      if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
        headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
 
      if (headers['X-Amz-Date'] || headers['x-amz-date'])
        this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
      else
        headers['X-Amz-Date'] = this.getDateTime()
    }
 
    delete headers.Authorization
    delete headers.authorization
  }
}
 
RequestSigner.prototype.sign = function() {
  if (!this.parsedPath) this.prepareRequest()
 
  if (this.request.signQuery) {
    this.parsedPath.query['X-Amz-Signature'] = this.signature()
  } else {
    this.request.headers.Authorization = this.authHeader()
  }
 
  this.request.path = this.formatPath()
 
  return this.request
}
 
RequestSigner.prototype.getDateTime = function() {
  if (!this.datetime) {
    var headers = this.request.headers,
      date = new Date(headers.Date || headers.date || new Date)
 
    this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
 
    // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
    if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
  }
  return this.datetime
}
 
RequestSigner.prototype.getDate = function() {
  return this.getDateTime().substr(0, 8)
}
 
RequestSigner.prototype.authHeader = function() {
  return [
    'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
    'SignedHeaders=' + this.signedHeaders(),
    'Signature=' + this.signature(),
  ].join(', ')
}
 
RequestSigner.prototype.signature = function() {
  var date = this.getDate(),
      cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
      kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
  if (!kCredentials) {
    kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
    kRegion = hmac(kDate, this.region)
    kService = hmac(kRegion, this.service)
    kCredentials = hmac(kService, 'aws4_request')
    credentialsCache.set(cacheKey, kCredentials)
  }
  return hmac(kCredentials, this.stringToSign(), 'hex')
}
 
RequestSigner.prototype.stringToSign = function() {
  return [
    'AWS4-HMAC-SHA256',
    this.getDateTime(),
    this.credentialString(),
    hash(this.canonicalString(), 'hex'),
  ].join('\n')
}
 
RequestSigner.prototype.canonicalString = function() {
  if (!this.parsedPath) this.prepareRequest()
 
  var pathStr = this.parsedPath.path,
      query = this.parsedPath.query,
      headers = this.request.headers,
      queryStr = '',
      normalizePath = this.service !== 's3',
      decodePath = this.service === 's3' || this.request.doNotEncodePath,
      decodeSlashesInPath = this.service === 's3',
      firstValOnly = this.service === 's3',
      bodyHash
 
  if (this.service === 's3' && this.request.signQuery) {
    bodyHash = 'UNSIGNED-PAYLOAD'
  } else if (this.isCodeCommitGit) {
    bodyHash = ''
  } else {
    bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
      hash(this.request.body || '', 'hex')
  }
 
  if (query) {
    queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
      if (!key) return obj
      obj[key] = !Array.isArray(query[key]) ? query[key] :
        (firstValOnly ? query[key][0] : query[key].slice().sort())
      return obj
    }, {})))
  }
  if (pathStr !== '/') {
    if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
    pathStr = pathStr.split('/').reduce(function(path, piece) {
      if (normalizePath && piece === '..') {
        path.pop()
      } else if (!normalizePath || piece !== '.') {
        if (decodePath) piece = querystring.unescape(piece)
        path.push(encodeRfc3986(querystring.escape(piece)))
      }
      return path
    }, []).join('/')
    if (pathStr[0] !== '/') pathStr = '/' + pathStr
    if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
  }
 
  return [
    this.request.method || 'GET',
    pathStr,
    queryStr,
    this.canonicalHeaders() + '\n',
    this.signedHeaders(),
    bodyHash,
  ].join('\n')
}
 
RequestSigner.prototype.canonicalHeaders = function() {
  var headers = this.request.headers
  function trimAll(header) {
    return header.toString().trim().replace(/\s+/g, ' ')
  }
  return Object.keys(headers)
    .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
    .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
    .join('\n')
}
 
RequestSigner.prototype.signedHeaders = function() {
  return Object.keys(this.request.headers)
    .map(function(key) { return key.toLowerCase() })
    .sort()
    .join(';')
}
 
RequestSigner.prototype.credentialString = function() {
  return [
    this.getDate(),
    this.region,
    this.service,
    'aws4_request',
  ].join('/')
}
 
RequestSigner.prototype.defaultCredentials = function() {
  var env = process.env
  return {
    accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
    secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
    sessionToken: env.AWS_SESSION_TOKEN,
  }
}
 
RequestSigner.prototype.parsePath = function() {
  var path = this.request.path || '/',
      queryIx = path.indexOf('?'),
      query = null
 
  if (queryIx >= 0) {
    query = querystring.parse(path.slice(queryIx + 1))
    path = path.slice(0, queryIx)
  }
 
  // S3 doesn't always encode characters > 127 correctly and
  // all services don't encode characters > 255 correctly
  // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
  if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
    path = path.split('/').map(function(piece) {
      return querystring.escape(querystring.unescape(piece))
    }).join('/')
  }
 
  this.parsedPath = {
    path: path,
    query: query,
  }
}
 
RequestSigner.prototype.formatPath = function() {
  var path = this.parsedPath.path,
      query = this.parsedPath.query
 
  if (!query) return path
 
  // Services don't support empty query string keys
  if (query[''] != null) delete query['']
 
  return path + '?' + encodeRfc3986(querystring.stringify(query))
}
 
aws4.RequestSigner = RequestSigner
 
aws4.sign = function(request, credentials) {
  return new RequestSigner(request, credentials).sign()
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/lru.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/aws4/lru.js

Statements: 25.37% (17 / 67)      Branches: 0% (0 / 24)      Functions: 27.27% (3 / 11)      Lines: 26.98% (17 / 63)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 981 1     1 1 1 1     1             1                             1       1                 1 1 1     1                                   1               1                           1              
module.exports = function(size) {
  return new LruCache(size)
}
 
function LruCache(size) {
  this.capacity = size | 0
  this.map = Object.create(null)
  this.list = new DoublyLinkedList()
}
 
LruCache.prototype.get = function(key) {
  var node = this.map[key]
  if (node == null) return undefined
  this.used(node)
  return node.val
}
 
LruCache.prototype.set = function(key, val) {
  var node = this.map[key]
  if (node != null) {
    node.val = val
  } else {
    if (!this.capacity) this.prune()
    if (!this.capacity) return false
    node = new DoublyLinkedNode(key, val)
    this.map[key] = node
    this.capacity--
  }
  this.used(node)
  return true
}
 
LruCache.prototype.used = function(node) {
  this.list.moveToFront(node)
}
 
LruCache.prototype.prune = function() {
  var node = this.list.pop()
  if (node != null) {
    delete this.map[node.key]
    this.capacity++
  }
}
 
 
function DoublyLinkedList() {
  this.firstNode = null
  this.lastNode = null
}
 
DoublyLinkedList.prototype.moveToFront = function(node) {
  if (this.firstNode == node) return
 
  this.remove(node)
 
  if (this.firstNode == null) {
    this.firstNode = node
    this.lastNode = node
    node.prev = null
    node.next = null
  } else {
    node.prev = null
    node.next = this.firstNode
    node.next.prev = node
    this.firstNode = node
  }
}
 
DoublyLinkedList.prototype.pop = function() {
  var lastNode = this.lastNode
  if (lastNode != null) {
    this.remove(lastNode)
  }
  return lastNode
}
 
DoublyLinkedList.prototype.remove = function(node) {
  if (this.firstNode == node) {
    this.firstNode = node.next
  } else if (node.prev != null) {
    node.prev.next = node.next
  }
  if (this.lastNode == node) {
    this.lastNode = node.prev
  } else if (node.next != null) {
    node.next.prev = node.prev
  }
}
 
 
function DoublyLinkedNode(key, val) {
  this.key = key
  this.val = val
  this.prev = null
  this.next = null
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/caseless/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/caseless/

Statements: 14.55% (8 / 55)      Branches: 0% (0 / 24)      Functions: 0% (0 / 13)      Lines: 17.02% (8 / 47)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/caseless/
File Statements Branches Functions Lines
index.js 14.55% (8 / 55) 0% (0 / 24) 0% (0 / 13) 17.02% (8 / 47)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/caseless/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/caseless/index.js

Statements: 14.55% (8 / 55)      Branches: 0% (0 / 24)      Functions: 0% (0 / 13)      Lines: 17.02% (8 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 691     1                           1                 1                   1             1         1 1                                      
function Caseless (dict) {
  this.dict = dict || {}
}
Caseless.prototype.set = function (name, value, clobber) {
  if (typeof name === 'object') {
    for (var i in name) {
      this.set(i, name[i], value)
    }
  } else {
    if (typeof clobber === 'undefined') clobber = true
    var has = this.has(name)
 
    if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
    else this.dict[has || name] = value
    return has
  }
}
Caseless.prototype.has = function (name) {
  var keys = Object.keys(this.dict)
    , name = name.toLowerCase()
    ;
  for (var i=0;i<keys.length;i++) {
    if (keys[i].toLowerCase() === name) return keys[i]
  }
  return false
}
Caseless.prototype.get = function (name) {
  name = name.toLowerCase()
  var result, _key
  var headers = this.dict
  Object.keys(headers).forEach(function (key) {
    _key = key.toLowerCase()
    if (name === _key) result = headers[key]
  })
  return result
}
Caseless.prototype.swap = function (name) {
  var has = this.has(name)
  if (has === name) return
  if (!has) throw new Error('There is no header than matches "'+name+'"')
  this.dict[name] = this.dict[has]
  delete this.dict[has]
}
Caseless.prototype.del = function (name) {
  var has = this.has(name)
  return delete this.dict[has || name]
}
 
module.exports = function (dict) {return new Caseless(dict)}
module.exports.httpify = function (resp, headers) {
  var c = new Caseless(headers)
  resp.setHeader = function (key, value, clobber) {
    if (typeof value === 'undefined') return
    return c.set(key, value, clobber)
  }
  resp.hasHeader = function (key) {
    return c.has(key)
  }
  resp.getHeader = function (key) {
    return c.get(key)
  }
  resp.removeHeader = function (key) {
    return c.del(key)
  }
  resp.headers = c.dict
  return c
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/lib/

Statements: 19.64% (22 / 112)      Branches: 0% (0 / 43)      Functions: 0% (0 / 20)      Lines: 20% (22 / 110)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/lib/
File Statements Branches Functions Lines
combined_stream.js 19.64% (22 / 112) 0% (0 / 43) 0% (0 / 20) 20% (22 / 110)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/lib/combined_stream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/lib/combined_stream.js

Statements: 19.64% (22 / 112)      Branches: 0% (0 / 43)      Functions: 0% (0 / 20)      Lines: 20% (22 / 110)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 1901 1 1   1 1                     1   1                     1               1                                               1           1                                                     1                             1             1       1                 1                     1         1         1           1                     1                                 1          
var util = require('util');
var Stream = require('stream').Stream;
var DelayedStream = require('delayed-stream');
 
module.exports = CombinedStream;
function CombinedStream() {
  this.writable = false;
  this.readable = true;
  this.dataSize = 0;
  this.maxDataSize = 2 * 1024 * 1024;
  this.pauseStreams = true;
 
  this._released = false;
  this._streams = [];
  this._currentStream = null;
}
util.inherits(CombinedStream, Stream);
 
CombinedStream.create = function(options) {
  var combinedStream = new this();
 
  options = options || {};
  for (var option in options) {
    combinedStream[option] = options[option];
  }
 
  return combinedStream;
};
 
CombinedStream.isStreamLike = function(stream) {
  return (typeof stream !== 'function')
    && (typeof stream !== 'string')
    && (typeof stream !== 'boolean')
    && (typeof stream !== 'number')
    && (!Buffer.isBuffer(stream));
};
 
CombinedStream.prototype.append = function(stream) {
  var isStreamLike = CombinedStream.isStreamLike(stream);
 
  if (isStreamLike) {
    if (!(stream instanceof DelayedStream)) {
      var newStream = DelayedStream.create(stream, {
        maxDataSize: Infinity,
        pauseStream: this.pauseStreams,
      });
      stream.on('data', this._checkDataSize.bind(this));
      stream = newStream;
    }
 
    this._handleErrors(stream);
 
    if (this.pauseStreams) {
      stream.pause();
    }
  }
 
  this._streams.push(stream);
  return this;
};
 
CombinedStream.prototype.pipe = function(dest, options) {
  Stream.prototype.pipe.call(this, dest, options);
  this.resume();
  return dest;
};
 
CombinedStream.prototype._getNext = function() {
  this._currentStream = null;
  var stream = this._streams.shift();
 
 
  if (typeof stream == 'undefined') {
    this.end();
    return;
  }
 
  if (typeof stream !== 'function') {
    this._pipeNext(stream);
    return;
  }
 
  var getStream = stream;
  getStream(function(stream) {
    var isStreamLike = CombinedStream.isStreamLike(stream);
    if (isStreamLike) {
      stream.on('data', this._checkDataSize.bind(this));
      this._handleErrors(stream);
    }
 
    this._pipeNext(stream);
  }.bind(this));
};
 
CombinedStream.prototype._pipeNext = function(stream) {
  this._currentStream = stream;
 
  var isStreamLike = CombinedStream.isStreamLike(stream);
  if (isStreamLike) {
    stream.on('end', this._getNext.bind(this));
    stream.pipe(this, {end: false});
    return;
  }
 
  var value = stream;
  this.write(value);
  this._getNext();
};
 
CombinedStream.prototype._handleErrors = function(stream) {
  var self = this;
  stream.on('error', function(err) {
    self._emitError(err);
  });
};
 
CombinedStream.prototype.write = function(data) {
  this.emit('data', data);
};
 
CombinedStream.prototype.pause = function() {
  if (!this.pauseStreams) {
    return;
  }
 
  if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
  this.emit('pause');
};
 
CombinedStream.prototype.resume = function() {
  if (!this._released) {
    this._released = true;
    this.writable = true;
    this._getNext();
  }
 
  if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
  this.emit('resume');
};
 
CombinedStream.prototype.end = function() {
  this._reset();
  this.emit('end');
};
 
CombinedStream.prototype.destroy = function() {
  this._reset();
  this.emit('close');
};
 
CombinedStream.prototype._reset = function() {
  this.writable = false;
  this._streams = [];
  this._currentStream = null;
};
 
CombinedStream.prototype._checkDataSize = function() {
  this._updateDataSize();
  if (this.dataSize <= this.maxDataSize) {
    return;
  }
 
  var message =
    'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
  this._emitError(new Error(message));
};
 
CombinedStream.prototype._updateDataSize = function() {
  this.dataSize = 0;
 
  var self = this;
  this._streams.forEach(function(stream) {
    if (!stream.dataSize) {
      return;
    }
 
    self.dataSize += stream.dataSize;
  });
 
  if (this._currentStream && this._currentStream.dataSize) {
    this.dataSize += this._currentStream.dataSize;
  }
};
 
CombinedStream.prototype._emitError = function(err) {
  this._reset();
  this.emit('error', err);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/

Statements: 22.95% (14 / 61)      Branches: 0% (0 / 14)      Functions: 0% (0 / 13)      Lines: 22.95% (14 / 61)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/
File Statements Branches Functions Lines
delayed_stream.js 22.95% (14 / 61) 0% (0 / 14) 0% (0 / 13) 22.95% (14 / 61)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js

Statements: 22.95% (14 / 61)      Branches: 0% (0 / 14)      Functions: 0% (0 / 13)      Lines: 22.95% (14 / 61)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 1091 1   1 1                   1   1                                               1               1       1               1       1                 1           1                           1                              
var Stream = require('stream').Stream;
var util = require('util');
 
module.exports = DelayedStream;
function DelayedStream() {
  this.source = null;
  this.dataSize = 0;
  this.maxDataSize = 1024 * 1024;
  this.pauseStream = true;
 
  this._maxDataSizeExceeded = false;
  this._released = false;
  this._bufferedEvents = [];
}
util.inherits(DelayedStream, Stream);
 
DelayedStream.create = function(source, options) {
  var delayedStream = new this();
 
  options = options || {};
  for (var option in options) {
    delayedStream[option] = options[option];
  }
 
  delayedStream.source = source;
 
  var realEmit = source.emit;
  source.emit = function() {
    delayedStream._handleEmit(arguments);
    return realEmit.apply(source, arguments);
  };
 
  source.on('error', function() {});
  if (delayedStream.pauseStream) {
    source.pause();
  }
 
  return delayedStream;
};
 
Object.defineProperty(DelayedStream.prototype, 'readable', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.source.readable;
  }
});
 
DelayedStream.prototype.setEncoding = function() {
  return this.source.setEncoding.apply(this.source, arguments);
};
 
DelayedStream.prototype.resume = function() {
  if (!this._released) {
    this.release();
  }
 
  this.source.resume();
};
 
DelayedStream.prototype.pause = function() {
  this.source.pause();
};
 
DelayedStream.prototype.release = function() {
  this._released = true;
 
  this._bufferedEvents.forEach(function(args) {
    this.emit.apply(this, args);
  }.bind(this));
  this._bufferedEvents = [];
};
 
DelayedStream.prototype.pipe = function() {
  var r = Stream.prototype.pipe.apply(this, arguments);
  this.resume();
  return r;
};
 
DelayedStream.prototype._handleEmit = function(args) {
  if (this._released) {
    this.emit.apply(this, args);
    return;
  }
 
  if (args[0] === 'data') {
    this.dataSize += args[1].length;
    this._checkIfMaxDataSizeExceeded();
  }
 
  this._bufferedEvents.push(args);
};
 
DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
  if (this._maxDataSizeExceeded) {
    return;
  }
 
  if (this.dataSize <= this.maxDataSize) {
    return;
  }
 
  this._maxDataSizeExceeded = true;
  var message =
    'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
  this.emit('error', new Error(message));
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/extend/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/extend/

Statements: 12.5% (5 / 40)      Branches: 0% (0 / 47)      Functions: 0% (0 / 3)      Lines: 12.5% (5 / 40)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/extend/
File Statements Branches Functions Lines
index.js 12.5% (5 / 40) 0% (0 / 47) 0% (0 / 3) 12.5% (5 / 40)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/extend/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/extend/index.js

Statements: 12.5% (5 / 40)      Branches: 0% (0 / 47)      Functions: 0% (0 / 3)      Lines: 12.5% (5 / 40)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88    1 1   1               1                                       1                                                                                                            
'use strict';
 
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
 
var isArray = function isArray(arr) {
	if (typeof Array.isArray === 'function') {
		return Array.isArray(arr);
	}
 
	return toStr.call(arr) === '[object Array]';
};
 
var isPlainObject = function isPlainObject(obj) {
	if (!obj || toStr.call(obj) !== '[object Object]') {
		return false;
	}
 
	var hasOwnConstructor = hasOwn.call(obj, 'constructor');
	var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
	// Not own constructor property must be Object
	if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
		return false;
	}
 
	// Own properties are enumerated firstly, so to speed up,
	// if last one is own, then all properties are own.
	var key;
	for (key in obj) {/**/}
 
	return typeof key === 'undefined' || hasOwn.call(obj, key);
};
 
module.exports = function extend() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0],
		i = 1,
		length = arguments.length,
		deep = false;
 
	// Handle a deep copy situation
	if (typeof target === 'boolean') {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	} else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {
		target = {};
	}
 
	for (; i < length; ++i) {
		options = arguments[i];
		// Only deal with non-null/undefined values
		if (options != null) {
			// Extend the base object
			for (name in options) {
				src = target[name];
				copy = options[name];
 
				// Prevent never-ending loop
				if (target !== copy) {
					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
						if (copyIsArray) {
							copyIsArray = false;
							clone = src && isArray(src) ? src : [];
						} else {
							clone = src && isPlainObject(src) ? src : {};
						}
 
						// Never move original objects, clone them
						target[name] = extend(deep, clone, copy);
 
					// Don't bring in undefined values
					} else if (typeof copy !== 'undefined') {
						target[name] = copy;
					}
				}
			}
		}
	}
 
	// Return the modified object
	return target;
};
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/forever-agent/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/forever-agent/

Statements: 19.75% (16 / 81)      Branches: 0% (0 / 53)      Functions: 0% (0 / 8)      Lines: 20% (16 / 80)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/forever-agent/
File Statements Branches Functions Lines
index.js 19.75% (16 / 81) 0% (0 / 53) 0% (0 / 8) 20% (16 / 80)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/forever-agent/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/forever-agent/index.js

Statements: 19.75% (16 / 81)      Branches: 0% (0 / 53)      Functions: 0% (0 / 8)      Lines: 20% (16 / 80)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 1401 1   1           1                     1                                                                 1   1     1 1 1                                       1                                                         1     1   1 1   1                                            
module.exports = ForeverAgent
ForeverAgent.SSL = ForeverAgentSSL
 
var util = require('util')
  , Agent = require('http').Agent
  , net = require('net')
  , tls = require('tls')
  , AgentSSL = require('https').Agent
  
function getConnectionName(host, port) {  
  var name = ''
  if (typeof host === 'string') {
    name = host + ':' + port
  } else {
    // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name.
    name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':')
  }
  return name
}    
 
function ForeverAgent(options) {
  var self = this
  self.options = options || {}
  self.requests = {}
  self.sockets = {}
  self.freeSockets = {}
  self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
  self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
  self.on('free', function(socket, host, port) {
    var name = getConnectionName(host, port)
 
    if (self.requests[name] && self.requests[name].length) {
      self.requests[name].shift().onSocket(socket)
    } else if (self.sockets[name].length < self.minSockets) {
      if (!self.freeSockets[name]) self.freeSockets[name] = []
      self.freeSockets[name].push(socket)
      
      // if an error happens while we don't use the socket anyway, meh, throw the socket away
      var onIdleError = function() {
        socket.destroy()
      }
      socket._onIdleError = onIdleError
      socket.on('error', onIdleError)
    } else {
      // If there are no pending requests just destroy the
      // socket and it will get removed from the pool. This
      // gets us out of timeout issues and allows us to
      // default to Connection:keep-alive.
      socket.destroy()
    }
  })
 
}
util.inherits(ForeverAgent, Agent)
 
ForeverAgent.defaultMinSockets = 5
 
 
ForeverAgent.prototype.createConnection = net.createConnection
ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
ForeverAgent.prototype.addRequest = function(req, host, port) {
  var name = getConnectionName(host, port)
  
  if (typeof host !== 'string') {
    var options = host
    port = options.port
    host = options.host
  }
 
  if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
    var idleSocket = this.freeSockets[name].pop()
    idleSocket.removeListener('error', idleSocket._onIdleError)
    delete idleSocket._onIdleError
    req._reusedSocket = true
    req.onSocket(idleSocket)
  } else {
    this.addRequestNoreuse(req, host, port)
  }
}
 
ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
  if (this.sockets[name]) {
    var index = this.sockets[name].indexOf(s)
    if (index !== -1) {
      this.sockets[name].splice(index, 1)
    }
  } else if (this.sockets[name] && this.sockets[name].length === 0) {
    // don't leak
    delete this.sockets[name]
    delete this.requests[name]
  }
  
  if (this.freeSockets[name]) {
    var index = this.freeSockets[name].indexOf(s)
    if (index !== -1) {
      this.freeSockets[name].splice(index, 1)
      if (this.freeSockets[name].length === 0) {
        delete this.freeSockets[name]
      }
    }
  }
 
  if (this.requests[name] && this.requests[name].length) {
    // If we have pending requests and a socket gets closed a new one
    // needs to be created to take over in the pool for the one that closed.
    this.createSocket(name, host, port).emit('free')
  }
}
 
function ForeverAgentSSL (options) {
  ForeverAgent.call(this, options)
}
util.inherits(ForeverAgentSSL, ForeverAgent)
 
ForeverAgentSSL.prototype.createConnection = createConnectionSSL
ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
 
function createConnectionSSL (port, host, options) {
  if (typeof port === 'object') {
    options = port;
  } else if (typeof host === 'object') {
    options = host;
  } else if (typeof options === 'object') {
    options = options;
  } else {
    options = {};
  }
 
  if (typeof port === 'number') {
    options.port = port;
  }
 
  if (typeof host === 'string') {
    options.host = host;
  }
 
  return tls.connect(options);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/

Statements: 16.67% (32 / 192)      Branches: 0% (0 / 121)      Functions: 0% (0 / 25)      Lines: 16.67% (32 / 192)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/
File Statements Branches Functions Lines
form_data.js 16.49% (31 / 188) 0% (0 / 119) 0% (0 / 23) 16.49% (31 / 188)
populate.js 25% (1 / 4) 0% (0 / 2) 0% (0 / 2) 25% (1 / 4)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/form_data.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/form_data.js

Statements: 16.49% (31 / 188)      Branches: 0% (0 / 119)      Functions: 0% (0 / 23)      Lines: 16.49% (31 / 188)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 4421 1 1 1 1 1 1 1 1 1     1     1                 1                       1 1   1                                                                     1                                                                 1                                                                                                             1                                                                                             1                                         1                                                                 1                         1       1                             1               1                           1                                             1                   1                                                   1                                                                                                                 1                
var CombinedStream = require('combined-stream');
var util = require('util');
var path = require('path');
var http = require('http');
var https = require('https');
var parseUrl = require('url').parse;
var fs = require('fs');
var mime = require('mime-types');
var asynckit = require('asynckit');
var populate = require('./populate.js');
 
// Public API
module.exports = FormData;
 
// make it a Stream
util.inherits(FormData, CombinedStream);
 
/**
 * Create readable "multipart/form-data" streams.
 * Can be used to submit forms
 * and file uploads to other web applications.
 *
 * @constructor
 */
function FormData() {
  if (!(this instanceof FormData)) {
    return new FormData();
  }
 
  this._overheadLength = 0;
  this._valueLength = 0;
  this._valuesToMeasure = [];
 
  CombinedStream.call(this);
}
 
FormData.LINE_BREAK = '\r\n';
FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
 
FormData.prototype.append = function(field, value, options) {
 
  options = options || {};
 
  // allow filename as single option
  if (typeof options == 'string') {
    options = {filename: options};
  }
 
  var append = CombinedStream.prototype.append.bind(this);
 
  // all that streamy business can't handle numbers
  if (typeof value == 'number') {
    value = '' + value;
  }
 
  // https://github.com/felixge/node-form-data/issues/38
  if (util.isArray(value)) {
    // Please convert your array into string
    // the way web server expects it
    this._error(new Error('Arrays are not supported.'));
    return;
  }
 
  var header = this._multiPartHeader(field, value, options);
  var footer = this._multiPartFooter();
 
  append(header);
  append(value);
  append(footer);
 
  // pass along options.knownLength
  this._trackLength(header, value, options);
};
 
FormData.prototype._trackLength = function(header, value, options) {
  var valueLength = 0;
 
  // used w/ getLengthSync(), when length is known.
  // e.g. for streaming directly from a remote server,
  // w/ a known file a size, and not wanting to wait for
  // incoming file to finish to get its size.
  if (options.knownLength != null) {
    valueLength += +options.knownLength;
  } else if (Buffer.isBuffer(value)) {
    valueLength = value.length;
  } else if (typeof value === 'string') {
    valueLength = Buffer.byteLength(value);
  }
 
  this._valueLength += valueLength;
 
  // @check why add CRLF? does this account for custom/multiple CRLFs?
  this._overheadLength +=
    Buffer.byteLength(header) +
    FormData.LINE_BREAK.length;
 
  // empty or either doesn't have path or not an http response
  if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) {
    return;
  }
 
  // no need to bother with the length
  if (!options.knownLength) {
    this._valuesToMeasure.push(value);
  }
};
 
FormData.prototype._lengthRetriever = function(value, callback) {
 
  if (value.hasOwnProperty('fd')) {
 
    // take read range into a account
    // `end` = Infinity –> read file till the end
    //
    // TODO: Looks like there is bug in Node fs.createReadStream
    // it doesn't respect `end` options without `start` options
    // Fix it when node fixes it.
    // https://github.com/joyent/node/issues/7819
    if (value.end != undefined && value.end != Infinity && value.start != undefined) {
 
      // when end specified
      // no need to calculate range
      // inclusive, starts with 0
      callback(null, value.end + 1 - (value.start ? value.start : 0));
 
    // not that fast snoopy
    } else {
      // still need to fetch file size from fs
      fs.stat(value.path, function(err, stat) {
 
        var fileSize;
 
        if (err) {
          callback(err);
          return;
        }
 
        // update final size based on the range options
        fileSize = stat.size - (value.start ? value.start : 0);
        callback(null, fileSize);
      });
    }
 
  // or http response
  } else if (value.hasOwnProperty('httpVersion')) {
    callback(null, +value.headers['content-length']);
 
  // or request stream http://github.com/mikeal/request
  } else if (value.hasOwnProperty('httpModule')) {
    // wait till response come back
    value.on('response', function(response) {
      value.pause();
      callback(null, +response.headers['content-length']);
    });
    value.resume();
 
  // something else
  } else {
    callback('Unknown stream');
  }
};
 
FormData.prototype._multiPartHeader = function(field, value, options) {
  // custom header specified (as string)?
  // it becomes responsible for boundary
  // (e.g. to handle extra CRLFs on .NET servers)
  if (typeof options.header == 'string') {
    return options.header;
  }
 
  var contentDisposition = this._getContentDisposition(value, options);
  var contentType = this._getContentType(value, options);
 
  var contents = '';
  var headers  = {
    // add custom disposition as third element or keep it two elements if not
    'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
    // if no content type. allow it to be empty array
    'Content-Type': [].concat(contentType || [])
  };
 
  // allow custom headers.
  if (typeof options.header == 'object') {
    populate(headers, options.header);
  }
 
  var header;
  for (var prop in headers) {
    header = headers[prop];
 
    // skip nullish headers.
    if (header == null) {
      continue;
    }
 
    // convert all headers to arrays.
    if (!Array.isArray(header)) {
      header = [header];
    }
 
    // add non-empty headers.
    if (header.length) {
      contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
    }
  }
 
  return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
};
 
FormData.prototype._getContentDisposition = function(value, options) {
 
  var contentDisposition;
 
  // custom filename takes precedence
  // fs- and request- streams have path property
  // formidable and the browser add a name property.
  var filename = options.filename || value.name || value.path;
 
  // or try http response
  if (!filename && value.readable && value.hasOwnProperty('httpVersion')) {
    filename = value.client._httpMessage.path;
  }
 
  if (filename) {
    contentDisposition = 'filename="' + path.basename(filename) + '"';
  }
 
  return contentDisposition;
};
 
FormData.prototype._getContentType = function(value, options) {
 
  // use custom content-type above all
  var contentType = options.contentType;
 
  // or try `name` from formidable, browser
  if (!contentType && value.name) {
    contentType = mime.lookup(value.name);
  }
 
  // or try `path` from fs-, request- streams
  if (!contentType && value.path) {
    contentType = mime.lookup(value.path);
  }
 
  // or if it's http-reponse
  if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
    contentType = value.headers['content-type'];
  }
 
  // or guess it from the filename
  if (!contentType && options.filename) {
    contentType = mime.lookup(options.filename);
  }
 
  // fallback to the default content type if `value` is not simple value
  if (!contentType && typeof value == 'object') {
    contentType = FormData.DEFAULT_CONTENT_TYPE;
  }
 
  return contentType;
};
 
FormData.prototype._multiPartFooter = function() {
  return function(next) {
    var footer = FormData.LINE_BREAK;
 
    var lastPart = (this._streams.length === 0);
    if (lastPart) {
      footer += this._lastBoundary();
    }
 
    next(footer);
  }.bind(this);
};
 
FormData.prototype._lastBoundary = function() {
  return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
};
 
FormData.prototype.getHeaders = function(userHeaders) {
  var header;
  var formHeaders = {
    'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
  };
 
  for (header in userHeaders) {
    if (userHeaders.hasOwnProperty(header)) {
      formHeaders[header.toLowerCase()] = userHeaders[header];
    }
  }
 
  return formHeaders;
};
 
FormData.prototype.getBoundary = function() {
  if (!this._boundary) {
    this._generateBoundary();
  }
 
  return this._boundary;
};
 
FormData.prototype._generateBoundary = function() {
  // This generates a 50 character boundary similar to those used by Firefox.
  // They are optimized for boyer-moore parsing.
  var boundary = '--------------------------';
  for (var i = 0; i < 24; i++) {
    boundary += Math.floor(Math.random() * 10).toString(16);
  }
 
  this._boundary = boundary;
};
 
// Note: getLengthSync DOESN'T calculate streams length
// As workaround one can calculate file size manually
// and add it as knownLength option
FormData.prototype.getLengthSync = function() {
  var knownLength = this._overheadLength + this._valueLength;
 
  // Don't get confused, there are 3 "internal" streams for each keyval pair
  // so it basically checks if there is any value added to the form
  if (this._streams.length) {
    knownLength += this._lastBoundary().length;
  }
 
  // https://github.com/form-data/form-data/issues/40
  if (!this.hasKnownLength()) {
    // Some async length retrievers are present
    // therefore synchronous length calculation is false.
    // Please use getLength(callback) to get proper length
    this._error(new Error('Cannot calculate proper length in synchronous way.'));
  }
 
  return knownLength;
};
 
// Public API to check if length of added values is known
// https://github.com/form-data/form-data/issues/196
// https://github.com/form-data/form-data/issues/262
FormData.prototype.hasKnownLength = function() {
  var hasKnownLength = true;
 
  if (this._valuesToMeasure.length) {
    hasKnownLength = false;
  }
 
  return hasKnownLength;
};
 
FormData.prototype.getLength = function(cb) {
  var knownLength = this._overheadLength + this._valueLength;
 
  if (this._streams.length) {
    knownLength += this._lastBoundary().length;
  }
 
  if (!this._valuesToMeasure.length) {
    process.nextTick(cb.bind(this, null, knownLength));
    return;
  }
 
  asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
    if (err) {
      cb(err);
      return;
    }
 
    values.forEach(function(length) {
      knownLength += length;
    });
 
    cb(null, knownLength);
  });
};
 
FormData.prototype.submit = function(params, cb) {
  var request
    , options
    , defaults = {method: 'post'}
    ;
 
  // parse provided url if it's string
  // or treat it as options object
  if (typeof params == 'string') {
 
    params = parseUrl(params);
    options = populate({
      port: params.port,
      path: params.pathname,
      host: params.hostname
    }, defaults);
 
  // use custom params
  } else {
 
    options = populate(params, defaults);
    // if no port provided use default one
    if (!options.port) {
      options.port = options.protocol == 'https:' ? 443 : 80;
    }
  }
 
  // put that good code in getHeaders to some use
  options.headers = this.getHeaders(params.headers);
 
  // https if specified, fallback to http in any other case
  if (options.protocol == 'https:') {
    request = https.request(options);
  } else {
    request = http.request(options);
  }
 
  // get content length and fire away
  this.getLength(function(err, length) {
    if (err) {
      this._error(err);
      return;
    }
 
    // add content length
    request.setHeader('Content-Length', length);
 
    this.pipe(request);
    if (cb) {
      request.on('error', cb);
      request.on('response', cb.bind(this, null));
    }
  }.bind(this));
 
  return request;
};
 
FormData.prototype._error = function(err) {
  if (!this.error) {
    this.error = err;
    this.pause();
    this.emit('error', err);
  }
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/populate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/lib/populate.js

Statements: 25% (1 / 4)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 25% (1 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12  1                    
// populates missing values
module.exports = function(dst, src) {
 
  Object.keys(src).forEach(function(prop)
  {
    dst[prop] = dst[prop] || src[prop];
  });
 
  return dst;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/

Statements: 35.9% (14 / 39)      Branches: 0% (0 / 16)      Functions: 0% (0 / 7)      Lines: 35.9% (14 / 39)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
parallel.js 21.43% (3 / 14) 0% (0 / 6) 0% (0 / 2) 21.43% (3 / 14)
serial.js 75% (3 / 4) 100% (0 / 0) 0% (0 / 1) 75% (3 / 4)
serialOrdered.js 35% (7 / 20) 0% (0 / 10) 0% (0 / 4) 35% (7 / 20)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 81              
module.exports =
{
  parallel      : require('./parallel.js'),
  serial        : require('./serial.js'),
  serialOrdered : require('./serialOrdered.js')
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/parallel.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/parallel.js

Statements: 21.43% (3 / 14)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 21.43% (3 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 451           1                   1                                                        
var iterate    = require('./lib/iterate.js')
  , initState  = require('./lib/state.js')
  , terminator = require('./lib/terminator.js')
  ;
 
// Public API
module.exports = parallel;
 
/**
 * Runs iterator over provided array elements in parallel
 *
 * @param   {array|object} list - array or object (named list) to iterate over
 * @param   {function} iterator - iterator to run
 * @param   {function} callback - invoked when all elements processed
 * @returns {function} - jobs terminator
 */
function parallel(list, iterator, callback)
{
  var state = initState(list);
 
  while (state.index < (state['keyedList'] || list).length)
  {
    iterate(list, iterator, state, function(error, result)
    {
      if (error)
      {
        callback(error, result);
        return;
      }
 
      // looks like it's the last one
      if (Object.keys(state.jobs).length === 0)
      {
        callback(null, state.results);
        return;
      }
    });
 
    state.index++;
  }
 
  return terminator.bind(state, callback);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/serial.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/serial.js

Statements: 75% (3 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 75% (3 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 191     1                   1          
var serialOrdered = require('./serialOrdered.js');
 
// Public API
module.exports = serial;
 
/**
 * Runs iterator over provided array elements in series
 *
 * @param   {array|object} list - array or object (named list) to iterate over
 * @param   {function} iterator - iterator to run
 * @param   {function} callback - invoked when all elements processed
 * @returns {function} - jobs terminator
 */
function serial(list, iterator, callback)
{
  return serialOrdered(list, iterator, null, callback);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/serialOrdered.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/serialOrdered.js

Statements: 35% (7 / 20)      Branches: 0% (0 / 10)      Functions: 0% (0 / 4)      Lines: 35% (7 / 20)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 771           1   1 1                     1                                                                             1                       1          
var iterate    = require('./lib/iterate.js')
  , initState  = require('./lib/state.js')
  , terminator = require('./lib/terminator.js')
  ;
 
// Public API
module.exports = serialOrdered;
// sorting helpers
module.exports.ascending  = ascending;
module.exports.descending = descending;
 
/**
 * Runs iterator over provided sorted array elements in series
 *
 * @param   {array|object} list - array or object (named list) to iterate over
 * @param   {function} iterator - iterator to run
 * @param   {function} sortMethod - custom sort function
 * @param   {function} callback - invoked when all elements processed
 * @returns {function} - jobs terminator
 */
function serialOrdered(list, iterator, sortMethod, callback)
{
  var state = initState(list, sortMethod);
 
  iterate(list, iterator, state, function iteratorHandler(error, result)
  {
    if (error)
    {
      callback(error, result);
      return;
    }
 
    state.index++;
 
    // are we there yet?
    if (state.index < (state['keyedList'] || list).length)
    {
      iterate(list, iterator, state, iteratorHandler);
      return;
    }
 
    // done here
    callback(null, state.results);
  });
 
  return terminator.bind(state, callback);
}
 
/*
 * -- Sort methods
 */
 
/**
 * sort helper to sort array elements in ascending order
 *
 * @param   {mixed} a - an item to compare
 * @param   {mixed} b - an item to compare
 * @returns {number} - comparison result
 */
function ascending(a, b)
{
  return a < b ? -1 : a > b ? 1 : 0;
}
 
/**
 * sort helper to sort array elements in descending order
 *
 * @param   {mixed} a - an item to compare
 * @param   {mixed} b - an item to compare
 * @returns {number} - comparison result
 */
function descending(a, b)
{
  return -1 * ascending(a, b);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/

Statements: 29.82% (17 / 57)      Branches: 0% (0 / 34)      Functions: 0% (0 / 13)      Lines: 30.36% (17 / 56)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/
File Statements Branches Functions Lines
abort.js 42.86% (3 / 7) 0% (0 / 2) 0% (0 / 2) 42.86% (3 / 7)
async.js 27.27% (3 / 11) 0% (0 / 2) 0% (0 / 4) 30% (3 / 10)
defer.js 33.33% (2 / 6) 0% (0 / 8) 0% (0 / 1) 33.33% (2 / 6)
iterate.js 22.22% (4 / 18) 0% (0 / 8) 0% (0 / 3) 22.22% (4 / 18)
state.js 28.57% (2 / 7) 0% (0 / 12) 0% (0 / 2) 28.57% (2 / 7)
terminator.js 37.5% (3 / 8) 0% (0 / 2) 0% (0 / 1) 37.5% (3 / 8)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/abort.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/abort.js

Statements: 42.86% (3 / 7)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 42.86% (3 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31  1             1                           1                
// API
module.exports = abort;
 
/**
 * Aborts leftover active jobs
 *
 * @param {object} state - current state object
 */
function abort(state)
{
  Object.keys(state.jobs).forEach(clean.bind(state));
 
  // reset leftover jobs
  state.jobs = {};
}
 
/**
 * Cleans up leftover job by invoking abort function for the provided job id
 *
 * @this  state
 * @param {string|number} key - job id to abort
 */
function clean(key)
{
  if (typeof this.jobs[key] == 'function')
  {
    this.jobs[key]();
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/async.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/async.js

Statements: 27.27% (3 / 11)      Branches: 0% (0 / 2)      Functions: 0% (0 / 4)      Lines: 30% (3 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 361     1                 1                                              
var defer = require('./defer.js');
 
// API
module.exports = async;
 
/**
 * Runs provided callback asynchronously
 * even if callback itself is not
 *
 * @param   {function} callback - callback to invoke
 * @returns {function} - augmented callback
 */
function async(callback)
{
  var isAsync = false;
 
  // check if async happened
  defer(function() { isAsync = true; });
 
  return function async_callback(err, result)
  {
    if (isAsync)
    {
      callback(err, result);
    }
    else
    {
      defer(function nextTick_callback()
      {
        callback(err, result);
      });
    }
  };
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/defer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/defer.js

Statements: 33.33% (2 / 6)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 33.33% (2 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 281             1                                        
module.exports = defer;
 
/**
 * Runs provided function on next iteration of the event loop
 *
 * @param {function} fn - function to run
 */
function defer(fn)
{
  var nextTick = typeof setImmediate == 'function'
    ? setImmediate
    : (
      typeof process == 'object' && typeof process.nextTick == 'function'
      ? process.nextTick
      : null
    );
 
  if (nextTick)
  {
    nextTick(fn);
  }
  else
  {
    setTimeout(fn, 0);
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/iterate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/iterate.js

Statements: 22.22% (4 / 18)      Branches: 0% (0 / 8)      Functions: 0% (0 / 3)      Lines: 22.22% (4 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 771         1                   1                                                                                     1                                    
var async = require('./async.js')
  , abort = require('./abort.js')
  ;
 
// API
module.exports = iterate;
 
/**
 * Iterates over each job object
 *
 * @param {array|object} list - array or object (named list) to iterate over
 * @param {function} iterator - iterator to run
 * @param {object} state - current job status
 * @param {function} callback - invoked when all elements processed
 */
function iterate(list, iterator, state, callback)
{
  // store current index
  var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
 
  state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
  {
    // don't repeat yourself
    // skip secondary callbacks
    if (!(key in state.jobs))
    {
      return;
    }
 
    // clean up jobs
    delete state.jobs[key];
 
    if (error)
    {
      // don't process rest of the results
      // stop still active jobs
      // and reset the list
      abort(state);
    }
    else
    {
      state.results[key] = output;
    }
 
    // return salvaged results
    callback(error, state.results);
  });
}
 
/**
 * Runs iterator over provided job element
 *
 * @param   {function} iterator - iterator to invoke
 * @param   {string|number} key - key/index of the element in the list of jobs
 * @param   {mixed} item - job description
 * @param   {function} callback - invoked after iterator is done with the job
 * @returns {function|mixed} - job abort function or something else
 */
function runJob(iterator, key, item, callback)
{
  var aborter;
 
  // allow shortcut if iterator expects only two arguments
  if (iterator.length == 2)
  {
    aborter = iterator(item, async(callback));
  }
  // otherwise go with full three arguments
  else
  {
    aborter = iterator(item, key, async(callback));
  }
 
  return aborter;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/state.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/state.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 12)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39  1                     1                                                    
// API
module.exports = state;
 
/**
 * Creates initial state object
 * for iteration over list
 *
 * @param   {array|object} list - list to iterate over
 * @param   {function|null} sortMethod - function to use for keys sort,
 *                                     or `null` to keep them as is
 * @returns {object} - initial state object
 */
function state(list, sortMethod)
{
  var isNamedList = !Array.isArray(list)
    , initState =
    {
      index    : 0,
      keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
      jobs     : {},
      results  : isNamedList ? {} : [],
      size     : isNamedList ? Object.keys(list).length : list.length
    }
    ;
 
  if (sortMethod)
  {
    // sort array keys based on it's values
    // sort object's keys just on own merit
    initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
    {
      return sortMethod(list[a], list[b]);
    });
  }
 
  return initState;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/terminator.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/form-data/node_modules/asynckit/lib/terminator.js

Statements: 37.5% (3 / 8)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 37.5% (3 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 311         1               1                                  
var abort = require('./abort.js')
  , async = require('./async.js')
  ;
 
// API
module.exports = terminator;
 
/**
 * Terminates jobs in the attached state context
 *
 * @this  AsyncKitState#
 * @param {function} callback - final callback to invoke after termination
 */
function terminator(callback)
{
  if (!Object.keys(this.jobs).length)
  {
    return;
  }
 
  // fast forward iteration index
  this.index = this.size;
 
  // abort jobs
  abort(this);
 
  // send back results we have so far
  async(callback)(null, this.results);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/

Statements: 65.96% (62 / 94)      Branches: 36.36% (8 / 22)      Functions: 8.7% (2 / 23)      Lines: 63.1% (53 / 84)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/
File Statements Branches Functions Lines
error.js 41.67% (5 / 12) 0% (0 / 2) 0% (0 / 1) 41.67% (5 / 12)
promise.js 69.51% (57 / 82) 40% (8 / 20) 9.09% (2 / 22) 66.67% (48 / 72)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/error.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/error.js

Statements: 41.67% (5 / 12)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 41.67% (5 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23    1     1 1                           1 1  
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = HARError;
function HARError(errors) {
  var message = 'validation failed';
 
  this.name = 'HARError';
  this.message = message;
  this.errors = errors;
 
  if (typeof Error.captureStackTrace === 'function') {
    Error.captureStackTrace(this, this.constructor);
  } else {
    this.stack = new Error(message).stack;
  }
}
 
HARError.prototype = Error.prototype;
module.exports = exports['default'];
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/promise.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/lib/node4/promise.js

Statements: 69.51% (57 / 82)      Branches: 40% (8 / 20)      Functions: 9.09% (2 / 22)      Lines: 66.67% (48 / 72)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133    1     1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1   1   1   1   1   1   2   18   1   1                                   1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1      
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.validate = validate;
exports.afterRequest = afterRequest;
exports.beforeRequest = beforeRequest;
exports.browser = browser;
exports.cache = cache;
exports.content = content;
exports.cookie = cookie;
exports.creator = creator;
exports.entry = entry;
exports.har = har;
exports.header = header;
exports.log = log;
exports.page = page;
exports.pageTimings = pageTimings;
exports.postData = postData;
exports.query = query;
exports.request = request;
exports.response = response;
exports.timings = timings;
 
var _harSchema = require('har-schema');
 
var schemas = _interopRequireWildcard(_harSchema);
 
var _ajv = require('ajv');
 
var _ajv2 = _interopRequireDefault(_ajv);
 
var _error = require('./error');
 
var _error2 = _interopRequireDefault(_error);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _interopRequireWildcard(obj) { Iif (obj && obj.__esModule) { return obj; } else { var newObj = {}; Eif (obj != null) { for (var key in obj) { Eif (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
 
var ajv = void 0;
 
function validate(name) {
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
 
  // validator config
  ajv = ajv || new _ajv2.default({
    allErrors: true,
    schemas: schemas
  });
 
  var validate = ajv.getSchema(name + '.json');
 
  return new Promise(function (resolve, reject) {
    var valid = validate(data);
 
    !valid ? reject(new _error2.default(validate.errors)) : resolve(data);
  });
}
 
function afterRequest(data) {
  return validate('afterRequest', data);
}
 
function beforeRequest(data) {
  return validate('beforeRequest', data);
}
 
function browser(data) {
  return validate('browser', data);
}
 
function cache(data) {
  return validate('cache', data);
}
 
function content(data) {
  return validate('content', data);
}
 
function cookie(data) {
  return validate('cookie', data);
}
 
function creator(data) {
  return validate('creator', data);
}
 
function entry(data) {
  return validate('entry', data);
}
 
function har(data) {
  return validate('har', data);
}
 
function header(data) {
  return validate('header', data);
}
 
function log(data) {
  return validate('log', data);
}
 
function page(data) {
  return validate('page', data);
}
 
function pageTimings(data) {
  return validate('pageTimings', data);
}
 
function postData(data) {
  return validate('postData', data);
}
 
function query(data) {
  return validate('query', data);
}
 
function request(data) {
  return validate('request', data);
}
 
function response(data) {
  return validate('response', data);
}
 
function timings(data) {
  return validate('timings', data);
}
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/

Statements: 17.26% (78 / 452)      Branches: 2.48% (6 / 242)      Functions: 0% (0 / 52)      Lines: 18.43% (75 / 407)      Ignored: 8 statements, 6 branches     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/
File Statements Branches Functions Lines
ajv.js 14.35% (34 / 237) 0% (0 / 139) 0% (0 / 23) 16.04% (34 / 212)
async.js 21.49% (26 / 121) 9.84% (6 / 61) 0% (0 / 16) 21.7% (23 / 106)
cache.js 50% (5 / 10) 100% (0 / 0) 0% (0 / 5) 50% (5 / 10)
keyword.js 13.11% (8 / 61) 0% (0 / 36) 0% (0 / 5) 14.04% (8 / 57)
v5.js 21.74% (5 / 23) 0% (0 / 6) 0% (0 / 3) 22.73% (5 / 22)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/ajv.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/ajv.js

Statements: 14.35% (34 / 237)      Branches: 0% (0 / 139)      Functions: 0% (0 / 23)      Lines: 16.04% (34 / 212)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422    1                       1   1   1 1 1 1 1   1 1 1       1               1                                                                                                 1                                               1                         1                                     1                     1                                   1                               1                   1                                       1                         1                                                             1                     1                                                                     1                                                               1                             1                                         1           1                 1               1               1           1                
'use strict';
 
var compileSchema = require('./compile')
  , resolve = require('./compile/resolve')
  , Cache = require('./cache')
  , SchemaObject = require('./compile/schema_obj')
  , stableStringify = require('json-stable-stringify')
  , formats = require('./compile/formats')
  , rules = require('./compile/rules')
  , v5 = require('./v5')
  , util = require('./compile/util')
  , async = require('./async')
  , co = require('co');
 
module.exports = Ajv;
 
Ajv.prototype.compileAsync = async.compile;
 
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.ValidationError = require('./compile/validation_error');
 
var META_SCHEMA_ID = 'http://json-schema.org/draft-04/schema';
var SCHEMA_URI_FORMAT = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i;
function SCHEMA_URI_FORMAT_FUNC(str) {
  return SCHEMA_URI_FORMAT.test(str);
}
 
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ];
 
/**
 * Creates validator instance.
 * Usage: `Ajv(opts)`
 * @param {Object} opts optional options
 * @return {Object} ajv instance
 */
function Ajv(opts) {
  if (!(this instanceof Ajv)) return new Ajv(opts);
  var self = this;
 
  opts = this._opts = util.copy(opts) || {};
  this._schemas = {};
  this._refs = {};
  this._fragments = {};
  this._formats = formats(opts.format);
  this._cache = opts.cache || new Cache;
  this._loadingSchemas = {};
  this._compilations = [];
  this.RULES = rules();
 
  // this is done on purpose, so that methods are bound to the instance
  // (without using bind) so that they can be used without the instance
  this.validate = validate;
  this.compile = compile;
  this.addSchema = addSchema;
  this.addMetaSchema = addMetaSchema;
  this.validateSchema = validateSchema;
  this.getSchema = getSchema;
  this.removeSchema = removeSchema;
  this.addFormat = addFormat;
  this.errorsText = errorsText;
 
  this._addSchema = _addSchema;
  this._compile = _compile;
 
  opts.loopRequired = opts.loopRequired || Infinity;
  if (opts.async || opts.transpile) async.setup(opts);
  if (opts.beautify === true) opts.beautify = { indent_size: 2 };
  if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
  this._metaOpts = getMetaSchemaOptions();
 
  if (opts.formats) addInitialFormats();
  addDraft4MetaSchema();
  if (opts.v5) v5.enable(this);
  if (typeof opts.meta == 'object') addMetaSchema(opts.meta);
  addInitialSchemas();
 
 
  /**
   * Validate data using schema
   * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize.
   * @param  {String|Object} schemaKeyRef key, ref or schema object
   * @param  {Any} data to be validated
   * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
   */
  function validate(schemaKeyRef, data) {
    var v;
    if (typeof schemaKeyRef == 'string') {
      v = getSchema(schemaKeyRef);
      if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
    } else {
      var schemaObj = _addSchema(schemaKeyRef);
      v = schemaObj.validate || _compile(schemaObj);
    }
 
    var valid = v(data);
    if (v.$async === true)
      return self._opts.async == '*' ? co(valid) : valid;
    self.errors = v.errors;
    return valid;
  }
 
 
  /**
   * Create validating function for passed schema.
   * @param  {Object} schema schema object
   * @param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
   * @return {Function} validating function
   */
  function compile(schema, _meta) {
    var schemaObj = _addSchema(schema, undefined, _meta);
    return schemaObj.validate || _compile(schemaObj);
  }
 
 
  /**
   * Adds schema to the instance.
   * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
   * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
   * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
   * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
   */
  function addSchema(schema, key, _skipValidation, _meta) {
    if (Array.isArray(schema)){
      for (var i=0; i<schema.length; i++) addSchema(schema[i], undefined, _skipValidation, _meta);
      return;
    }
    // can key/id have # inside?
    key = resolve.normalizeId(key || schema.id);
    checkUnique(key);
    self._schemas[key] = _addSchema(schema, _skipValidation, _meta, true);
  }
 
 
  /**
   * Add schema that will be used to validate other schemas
   * options in META_IGNORE_OPTIONS are alway set to false
   * @param {Object} schema schema object
   * @param {String} key optional schema key
   * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
   */
  function addMetaSchema(schema, key, skipValidation) {
    addSchema(schema, key, skipValidation, true);
  }
 
 
  /**
   * Validate schema
   * @param {Object} schema schema to validate
   * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
   * @return {Boolean} true if schema is valid
   */
  function validateSchema(schema, throwOrLogError) {
    var $schema = schema.$schema || self._opts.defaultMeta || defaultMeta();
    var currentUriFormat = self._formats.uri;
    self._formats.uri = typeof currentUriFormat == 'function'
                        ? SCHEMA_URI_FORMAT_FUNC
                        : SCHEMA_URI_FORMAT;
    var valid;
    try { valid = validate($schema, schema); }
    finally { self._formats.uri = currentUriFormat; }
    if (!valid && throwOrLogError) {
      var message = 'schema is invalid: ' + errorsText();
      if (self._opts.validateSchema == 'log') console.error(message);
      else throw new Error(message);
    }
    return valid;
  }
 
 
  function defaultMeta() {
    var meta = self._opts.meta;
    self._opts.defaultMeta = typeof meta == 'object'
                              ? meta.id || meta
                              : self._opts.v5
                                ? v5.META_SCHEMA_ID
                                : META_SCHEMA_ID;
    return self._opts.defaultMeta;
  }
 
 
  /**
   * Get compiled schema from the instance by `key` or `ref`.
   * @param  {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
   * @return {Function} schema validating function (with property `schema`).
   */
  function getSchema(keyRef) {
    var schemaObj = _getSchemaObj(keyRef);
    switch (typeof schemaObj) {
      case 'object': return schemaObj.validate || _compile(schemaObj);
      case 'string': return getSchema(schemaObj);
      case 'undefined': return _getSchemaFragment(keyRef);
    }
  }
 
 
  function _getSchemaFragment(ref) {
    var res = resolve.schema.call(self, { schema: {} }, ref);
    if (res) {
      var schema = res.schema
        , root = res.root
        , baseId = res.baseId;
      var v = compileSchema.call(self, schema, root, undefined, baseId);
      self._fragments[ref] = new SchemaObject({
        ref: ref,
        fragment: true,
        schema: schema,
        root: root,
        baseId: baseId,
        validate: v
      });
      return v;
    }
  }
 
 
  function _getSchemaObj(keyRef) {
    keyRef = resolve.normalizeId(keyRef);
    return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
  }
 
 
  /**
   * Remove cached schema(s).
   * If no parameter is passed all schemas but meta-schemas are removed.
   * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
   * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
   * @param  {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
   */
  function removeSchema(schemaKeyRef) {
    if (schemaKeyRef instanceof RegExp) {
      _removeAllSchemas(self._schemas, schemaKeyRef);
      _removeAllSchemas(self._refs, schemaKeyRef);
      return;
    }
    switch (typeof schemaKeyRef) {
      case 'undefined':
        _removeAllSchemas(self._schemas);
        _removeAllSchemas(self._refs);
        self._cache.clear();
        return;
      case 'string':
        var schemaObj = _getSchemaObj(schemaKeyRef);
        if (schemaObj) self._cache.del(schemaObj.jsonStr);
        delete self._schemas[schemaKeyRef];
        delete self._refs[schemaKeyRef];
        return;
      case 'object':
        var jsonStr = stableStringify(schemaKeyRef);
        self._cache.del(jsonStr);
        var id = schemaKeyRef.id;
        if (id) {
          id = resolve.normalizeId(id);
          delete self._schemas[id];
          delete self._refs[id];
        }
    }
  }
 
 
  function _removeAllSchemas(schemas, regex) {
    for (var keyRef in schemas) {
      var schemaObj = schemas[keyRef];
      if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
        self._cache.del(schemaObj.jsonStr);
        delete schemas[keyRef];
      }
    }
  }
 
 
  function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
    if (typeof schema != 'object') throw new Error('schema should be object');
    var jsonStr = stableStringify(schema);
    var cached = self._cache.get(jsonStr);
    if (cached) return cached;
 
    shouldAddSchema = shouldAddSchema || self._opts.addUsedSchema !== false;
 
    var id = resolve.normalizeId(schema.id);
    if (id && shouldAddSchema) checkUnique(id);
 
    var willValidate = self._opts.validateSchema !== false && !skipValidation;
    var recursiveMeta;
    if (willValidate && !(recursiveMeta = schema.id && schema.id == schema.$schema))
      validateSchema(schema, true);
 
    var localRefs = resolve.ids.call(self, schema);
 
    var schemaObj = new SchemaObject({
      id: id,
      schema: schema,
      localRefs: localRefs,
      jsonStr: jsonStr,
      meta: meta
    });
 
    if (id[0] != '#' && shouldAddSchema) self._refs[id] = schemaObj;
    self._cache.put(jsonStr, schemaObj);
 
    if (willValidate && recursiveMeta) validateSchema(schema, true);
 
    return schemaObj;
  }
 
 
  function _compile(schemaObj, root) {
    if (schemaObj.compiling) {
      schemaObj.validate = callValidate;
      callValidate.schema = schemaObj.schema;
      callValidate.errors = null;
      callValidate.root = root ? root : callValidate;
      if (schemaObj.schema.$async === true)
        callValidate.$async = true;
      return callValidate;
    }
    schemaObj.compiling = true;
 
    var currentOpts;
    if (schemaObj.meta) {
      currentOpts = self._opts;
      self._opts = self._metaOpts;
    }
 
    var v;
    try { v = compileSchema.call(self, schemaObj.schema, root, schemaObj.localRefs); }
    finally {
      schemaObj.compiling = false;
      if (schemaObj.meta) self._opts = currentOpts;
    }
 
    schemaObj.validate = v;
    schemaObj.refs = v.refs;
    schemaObj.refVal = v.refVal;
    schemaObj.root = v.root;
    return v;
 
 
    function callValidate() {
      var _validate = schemaObj.validate;
      var result = _validate.apply(null, arguments);
      callValidate.errors = _validate.errors;
      return result;
    }
  }
 
 
  /**
   * Convert array of error message objects to string
   * @param  {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
   * @param  {Object} options optional options with properties `separator` and `dataVar`.
   * @return {String} human readable string with all errors descriptions
   */
  function errorsText(errors, options) {
    errors = errors || self.errors;
    if (!errors) return 'No errors';
    options = options || {};
    var separator = options.separator === undefined ? ', ' : options.separator;
    var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
 
    var text = '';
    for (var i=0; i<errors.length; i++) {
      var e = errors[i];
      if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
    }
    return text.slice(0, -separator.length);
  }
 
 
  /**
   * Add custom format
   * @param {String} name format name
   * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
   */
  function addFormat(name, format) {
    if (typeof format == 'string') format = new RegExp(format);
    self._formats[name] = format;
  }
 
 
  function addDraft4MetaSchema() {
    if (self._opts.meta !== false) {
      var metaSchema = require('./refs/json-schema-draft-04.json');
      addMetaSchema(metaSchema, META_SCHEMA_ID, true);
      self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
    }
  }
 
 
  function addInitialSchemas() {
    var optsSchemas = self._opts.schemas;
    if (!optsSchemas) return;
    if (Array.isArray(optsSchemas)) addSchema(optsSchemas);
    else for (var key in optsSchemas) addSchema(optsSchemas[key], key);
  }
 
 
  function addInitialFormats() {
    for (var name in self._opts.formats) {
      var format = self._opts.formats[name];
      addFormat(name, format);
    }
  }
 
 
  function checkUnique(id) {
    if (self._schemas[id] || self._refs[id])
      throw new Error('schema with key or id "' + id + '" already exists');
  }
 
 
  function getMetaSchemaOptions() {
    var metaOpts = util.copy(self._opts);
    for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
      delete metaOpts[META_IGNORE_OPTIONS[i]];
    return metaOpts;
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/async.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/async.js

Statements: 21.49% (26 / 121)      Branches: 9.84% (6 / 61)      Functions: 0% (0 / 16)      Lines: 21.7% (23 / 106)      Ignored: 8 statements, 6 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220    1           1   1           1         1             1     1                                                     1                 1             1         1         1             1                       1         1         1                           1         1                       1                                       1                   1                                               1                           1              
'use strict';
 
module.exports = {
  setup: setupAsync,
  compile: compileAsync
};
 
 
var util = require('./compile/util');
 
var ASYNC = {
  '*': checkGenerators,
  'co*': checkGenerators,
  'es7': checkAsyncFunction
};
 
var TRANSPILE = {
  'nodent': getNodent,
  'regenerator': getRegenerator
};
 
var MODES = [
  { async: 'co*' },
  { async: 'es7', transpile: 'nodent' },
  { async: 'co*', transpile: 'regenerator' }
];
 
 
var regenerator, nodent;
 
 
function setupAsync(opts, required) {
  if (required !== false) required = true;
  var async = opts.async
    , transpile = opts.transpile
    , check;
 
  switch (typeof transpile) {
    case 'string':
      var get = TRANSPILE[transpile];
      if (!get) throw new Error('bad transpiler: ' + transpile);
      return (opts._transpileFunc = get(opts, required));
    case 'undefined':
    case 'boolean':
      if (typeof async == 'string') {
        check = ASYNC[async];
        if (!check) throw new Error('bad async mode: ' + async);
        return (opts.transpile = check(opts, required));
      }
 
      for (var i=0; i<MODES.length; i++) {
        var _opts = MODES[i];
        if (setupAsync(_opts, false)) {
          util.copy(_opts, opts);
          return opts.transpile;
        }
      }
      /* istanbul ignore next */
      throw new Error('generators, nodent and regenerator are not available');
    case 'function':
      return (opts._transpileFunc = opts.transpile);
    default:
      throw new Error('bad transpiler: ' + transpile);
  }
}
 
 
function checkGenerators(opts, required) {
  /* jshint evil: true */
  try {
    (new Function('(function*(){})()'))();
    return true;
  } catch(e) {
    /* istanbul ignore next */
    if (required) throw new Error('generators not supported');
  }
}
 
 
function checkAsyncFunction(opts, required) {
  /* jshint evil: true */
  try {
    (new Function('(async function(){})()'))();
    /* istanbul ignore next */
    return true;
  } catch(e) {
    if (required) throw new Error('es7 async functions not supported');
  }
}
 
 
function getRegenerator(opts, required) {
  try {
    if (!regenerator) {
      var name = 'regenerator';
      regenerator = require(name);
      regenerator.runtime();
    }
    if (!opts.async || opts.async === true)
      opts.async = 'es7';
    return regeneratorTranspile;
  } catch(e) {
    /* istanbul ignore next */
    if (required) throw new Error('regenerator not available');
  }
}
 
 
function regeneratorTranspile(code) {
  return regenerator.compile(code).code;
}
 
 
function getNodent(opts, required) {
  /* jshint evil: true */
  try {
    if (!nodent) {
      var name = 'nodent';
      nodent = require(name)({ log: false, dontInstallRequireHook: true });
    }
    if (opts.async != 'es7') {
      if (opts.async && opts.async !== true) console.warn('nodent transpiles only es7 async functions');
      opts.async = 'es7';
    }
    return nodentTranspile;
  } catch(e) {
    /* istanbul ignore next */
    if (required) throw new Error('nodent not available');
  }
}
 
 
function nodentTranspile(code) {
  return nodent.compile(code, '', { promises: true, sourcemap: false }).code;
}
 
 
/**
 * Creates validating function for passed schema with asynchronous loading of missing schemas.
 * `loadSchema` option should be a function that accepts schema uri and node-style callback.
 * @this  Ajv
 * @param {Object}   schema schema object
 * @param {Function} callback node-style callback, it is always called with 2 parameters: error (or null) and validating function.
 */
function compileAsync(schema, callback) {
  /* eslint no-shadow: 0 */
  /* jshint validthis: true */
  var schemaObj;
  var self = this;
  try {
    schemaObj = this._addSchema(schema);
  } catch(e) {
    setTimeout(function() { callback(e); });
    return;
  }
  if (schemaObj.validate) {
    setTimeout(function() { callback(null, schemaObj.validate); });
  } else {
    if (typeof this._opts.loadSchema != 'function')
      throw new Error('options.loadSchema should be a function');
    _compileAsync(schema, callback, true);
  }
 
 
  function _compileAsync(schema, callback, firstCall) {
    var validate;
    try { validate = self.compile(schema); }
    catch(e) {
      if (e.missingSchema) loadMissingSchema(e);
      else deferCallback(e);
      return;
    }
    deferCallback(null, validate);
 
    function loadMissingSchema(e) {
      var ref = e.missingSchema;
      if (self._refs[ref] || self._schemas[ref])
        return callback(new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'));
      var _callbacks = self._loadingSchemas[ref];
      if (_callbacks) {
        if (typeof _callbacks == 'function')
          self._loadingSchemas[ref] = [_callbacks, schemaLoaded];
        else
          _callbacks[_callbacks.length] = schemaLoaded;
      } else {
        self._loadingSchemas[ref] = schemaLoaded;
        self._opts.loadSchema(ref, function (err, sch) {
          var _callbacks = self._loadingSchemas[ref];
          delete self._loadingSchemas[ref];
          if (typeof _callbacks == 'function') {
            _callbacks(err, sch);
          } else {
            for (var i=0; i<_callbacks.length; i++)
              _callbacks[i](err, sch);
          }
        });
      }
 
      function schemaLoaded(err, sch) {
        if (err) return callback(err);
        if (!(self._refs[ref] || self._schemas[ref])) {
          try {
            self.addSchema(sch, ref);
          } catch(e) {
            callback(e);
            return;
          }
        }
        _compileAsync(schema, callback);
      }
    }
 
    function deferCallback(err, validate) {
      if (firstCall) setTimeout(function() { callback(err, validate); });
      else return callback(err, validate);
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/cache.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/cache.js

Statements: 50% (5 / 10)      Branches: 100% (0 / 0)      Functions: 0% (0 / 5)      Lines: 50% (5 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28      1         1         1         1         1        
'use strict';
 
 
var Cache = module.exports = function Cache() {
  this._cache = {};
};
 
 
Cache.prototype.put = function Cache_put(key, value) {
  this._cache[key] = value;
};
 
 
Cache.prototype.get = function Cache_get(key) {
  return this._cache[key];
};
 
 
Cache.prototype.del = function Cache_del(key) {
  delete this._cache[key];
};
 
 
Cache.prototype.clear = function Cache_clear() {
  this._cache = {};
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/keyword.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/keyword.js

Statements: 13.11% (8 / 61)      Branches: 0% (0 / 36)      Functions: 0% (0 / 5)      Lines: 14.04% (8 / 57)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131    1 1   1                       1                                                                                           1                                                   1                       1                       1                                  
'use strict';
 
var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i;
var customRuleCode = require('./dotjs/custom');
 
module.exports = {
  add: addKeyword,
  get: getKeyword,
  remove: removeKeyword
};
 
/**
 * Define custom keyword
 * @this  Ajv
 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
 */
function addKeyword(keyword, definition) {
  /* jshint validthis: true */
  /* eslint no-shadow: 0 */
  var RULES = this.RULES;
 
  if (RULES.keywords[keyword])
    throw new Error('Keyword ' + keyword + ' is already defined');
 
  if (!IDENTIFIER.test(keyword))
    throw new Error('Keyword ' + keyword + ' is not a valid identifier');
 
  if (definition) {
    if (definition.macro && definition.valid !== undefined)
      throw new Error('"valid" option cannot be used with macro keywords');
 
    var dataType = definition.type;
    if (Array.isArray(dataType)) {
      var i, len = dataType.length;
      for (i=0; i<len; i++) checkDataType(dataType[i]);
      for (i=0; i<len; i++) _addRule(keyword, dataType[i], definition);
    } else {
      if (dataType) checkDataType(dataType);
      _addRule(keyword, dataType, definition);
    }
 
    var $data = definition.$data === true && this._opts.v5;
    if ($data && !definition.validate)
      throw new Error('$data support: "validate" function is not defined');
 
    var metaSchema = definition.metaSchema;
    if (metaSchema) {
      if ($data) {
        metaSchema = {
          anyOf: [
            metaSchema,
            { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#/definitions/$data' }
          ]
        };
      }
      definition.validateSchema = this.compile(metaSchema, true);
    }
  }
 
  RULES.keywords[keyword] = RULES.all[keyword] = true;
 
 
  function _addRule(keyword, dataType, definition) {
    var ruleGroup;
    for (var i=0; i<RULES.length; i++) {
      var rg = RULES[i];
      if (rg.type == dataType) {
        ruleGroup = rg;
        break;
      }
    }
 
    if (!ruleGroup) {
      ruleGroup = { type: dataType, rules: [] };
      RULES.push(ruleGroup);
    }
 
    var rule = {
      keyword: keyword,
      definition: definition,
      custom: true,
      code: customRuleCode
    };
    ruleGroup.rules.push(rule);
    RULES.custom[keyword] = rule;
  }
 
 
  function checkDataType(dataType) {
    if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType);
  }
}
 
 
/**
 * Get keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
 */
function getKeyword(keyword) {
  /* jshint validthis: true */
  var rule = this.RULES.custom[keyword];
  return rule ? rule.definition : this.RULES.keywords[keyword] || false;
}
 
 
/**
 * Remove keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 */
function removeKeyword(keyword) {
  /* jshint validthis: true */
  var RULES = this.RULES;
  delete RULES.keywords[keyword];
  delete RULES.all[keyword];
  delete RULES.custom[keyword];
  for (var i=0; i<RULES.length; i++) {
    var rules = RULES[i].rules;
    for (var j=0; j<rules.length; j++) {
      if (rules[j].keyword == keyword) {
        rules.splice(j, 1);
        break;
      }
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/v5.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/v5.js

Statements: 21.74% (5 / 23)      Branches: 0% (0 / 6)      Functions: 0% (0 / 3)      Lines: 22.73% (5 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54    1   1           1                                                 1                       1            
'use strict';
 
var META_SCHEMA_ID = 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json';
 
module.exports = {
  enable: enableV5,
  META_SCHEMA_ID: META_SCHEMA_ID
};
 
 
function enableV5(ajv) {
  var inlineFunctions = {
    'switch': require('./dotjs/switch'),
    'constant': require('./dotjs/constant'),
    '_formatLimit': require('./dotjs/_formatLimit'),
    'patternRequired': require('./dotjs/patternRequired')
  };
 
  if (ajv._opts.meta !== false) {
    var metaSchema = require('./refs/json-schema-v5.json');
    ajv.addMetaSchema(metaSchema, META_SCHEMA_ID);
  }
  _addKeyword('constant');
  ajv.addKeyword('contains', { type: 'array', macro: containsMacro });
 
  _addKeyword('formatMaximum', 'string', inlineFunctions._formatLimit);
  _addKeyword('formatMinimum', 'string', inlineFunctions._formatLimit);
  ajv.addKeyword('formatExclusiveMaximum');
  ajv.addKeyword('formatExclusiveMinimum');
 
  ajv.addKeyword('patternGroups'); // implemented in properties.jst
  _addKeyword('patternRequired', 'object');
  _addKeyword('switch');
 
 
  function _addKeyword(keyword, types, inlineFunc) {
    var definition = {
      inline: inlineFunc || inlineFunctions[keyword],
      statements: true,
      errors: 'full'
    };
    if (types) definition.type = types;
    ajv.addKeyword(keyword, definition);
  }
}
 
 
function containsMacro(schema) {
  return {
    not: { items: { not: schema } }
  };
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/

Statements: 19.22% (123 / 640)      Branches: 0.24% (1 / 424)      Functions: 1.41% (1 / 71)      Lines: 21.71% (122 / 562)      Ignored: 1 statement, 1 branch     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/
File Statements Branches Functions Lines
_rules.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
equal.js 2.86% (1 / 35) 0% (0 / 36) 0% (0 / 1) 4.17% (1 / 24)
formats.js 30.49% (25 / 82) 0% (0 / 58) 0% (0 / 10) 36.23% (25 / 69)
index.js 15.3% (28 / 183) 1.04% (1 / 96) 0% (0 / 19) 16.57% (28 / 169)
resolve.js 14.37% (24 / 167) 0% (0 / 136) 0% (0 / 13) 16.44% (24 / 146)
rules.js 12.5% (2 / 16) 100% (0 / 0) 0% (0 / 3) 12.5% (2 / 16)
schema_obj.js 75% (3 / 4) 100% (0 / 0) 0% (0 / 1) 75% (3 / 4)
ucs2length.js 10% (1 / 10) 0% (0 / 7) 0% (0 / 1) 11.11% (1 / 9)
util.js 25.19% (34 / 135) 0% (0 / 91) 4.55% (1 / 22) 28.21% (33 / 117)
validation_error.js 57.14% (4 / 7) 100% (0 / 0) 0% (0 / 1) 57.14% (4 / 7)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/_rules.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/_rules.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30      1                                                    
'use strict';
 
//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
  '$ref': require('../dotjs/ref'),
  allOf: require('../dotjs/allOf'),
  anyOf: require('../dotjs/anyOf'),
  dependencies: require('../dotjs/dependencies'),
  'enum': require('../dotjs/enum'),
  format: require('../dotjs/format'),
  items: require('../dotjs/items'),
  maximum: require('../dotjs/_limit'),
  minimum: require('../dotjs/_limit'),
  maxItems: require('../dotjs/_limitItems'),
  minItems: require('../dotjs/_limitItems'),
  maxLength: require('../dotjs/_limitLength'),
  minLength: require('../dotjs/_limitLength'),
  maxProperties: require('../dotjs/_limitProperties'),
  minProperties: require('../dotjs/_limitProperties'),
  multipleOf: require('../dotjs/multipleOf'),
  not: require('../dotjs/not'),
  oneOf: require('../dotjs/oneOf'),
  pattern: require('../dotjs/pattern'),
  properties: require('../dotjs/properties'),
  required: require('../dotjs/required'),
  uniqueItems: require('../dotjs/uniqueItems'),
  validate: require('../dotjs/validate')
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/equal.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/equal.js

Statements: 2.86% (1 / 35)      Branches: 0% (0 / 36)      Functions: 0% (0 / 1)      Lines: 4.17% (1 / 24)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47        1                                                                                    
'use strict';
 
/*eslint complexity: 0*/
 
module.exports = function equal(a, b) {
  if (a === b) return true;
 
  var arrA = Array.isArray(a)
    , arrB = Array.isArray(b)
    , i;
 
  if (arrA && arrB) {
    if (a.length != b.length) return false;
    for (i = 0; i < a.length; i++)
      if (!equal(a[i], b[i])) return false;
    return true;
  }
 
  if (arrA != arrB) return false;
 
  if (a && b && typeof a === 'object' && typeof b === 'object') {
    var keys = Object.keys(a);
    if (keys.length !== Object.keys(b).length) return false;
 
    var dateA = a instanceof Date
      , dateB = b instanceof Date;
    if (dateA && dateB) return a.getTime() == b.getTime();
    if (dateA != dateB) return false;
 
    var regexpA = a instanceof RegExp
      , regexpB = b instanceof RegExp;
    if (regexpA && regexpB) return a.toString() == b.toString();
    if (regexpA != regexpB) return false;
 
    for (i = 0; i < keys.length; i++)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
 
    for (i = 0; i < keys.length; i++)
      if(!equal(a[keys[i]], b[keys[i]])) return false;
 
    return true;
  }
 
  return false;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/formats.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/formats.js

Statements: 30.49% (25 / 82)      Branches: 0% (0 / 58)      Functions: 0% (0 / 10)      Lines: 36.23% (25 / 69)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166    1   1 1 1 1 1 1 1 1     1   1                         1                                                       1                               1             1                     1                       1 1             1             1 1           1                   1               1                         1                  
'use strict';
 
var util = require('./util');
 
var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/;
var DAYS = [0,31,29,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
var HOSTNAME = /^[0-9a-z](?:(?:[-0-9a-z]{0,61})?[0-9a-z])?(\.[0-9a-z](?:(?:[-0-9a-z]{0,61})?[0-9a-z])?)*$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i;
var UUID = /^(?:urn\:uuid\:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~\/]|~0|~1)*)*$|^\#(?:\/(?:[a-z0-9_\-\.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:\#|(?:\/(?:[^~\/]|~0|~1)*)*)$/;
 
 
module.exports = formats;
 
function formats(mode) {
  mode = mode == 'full' ? 'full' : 'fast';
  var formatDefs = util.copy(formats[mode]);
  for (var fName in formats.compare) {
    formatDefs[fName] = {
      validate: formatDefs[fName],
      compare: formats.compare[fName]
    };
  }
  return formatDefs;
}
 
 
formats.fast = {
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
  date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
  time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
  'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
  // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
  uri: /^(?:[a-z][a-z0-9+-.]*)?(?:\:|\/)\/?[^\s]*$/i,
  // email (sources from jsen validator):
  // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
  // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
  email: /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
  hostname: HOSTNAME,
  // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  // uuid: http://tools.ietf.org/html/rfc4122
  uuid: UUID,
  // JSON-pointer: https://tools.ietf.org/html/rfc6901
  // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
  'json-pointer': JSON_POINTER,
  // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
  'relative-json-pointer': RELATIVE_JSON_POINTER
};
 
 
formats.full = {
  date: date,
  time: time,
  'date-time': date_time,
  uri: uri,
  email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
  hostname: hostname,
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  uuid: UUID,
  'json-pointer': JSON_POINTER,
  'relative-json-pointer': RELATIVE_JSON_POINTER
};
 
 
formats.compare = {
  date: compareDate,
  time: compareTime,
  'date-time': compareDateTime
};
 
 
function date(str) {
  // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
  var matches = str.match(DATE);
  if (!matches) return false;
 
  var month = +matches[1];
  var day = +matches[2];
  return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month];
}
 
 
function time(str, full) {
  var matches = str.match(TIME);
  if (!matches) return false;
 
  var hour = matches[1];
  var minute = matches[2];
  var second = matches[3];
  var timeZone = matches[5];
  return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone);
}
 
 
var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  var dateTime = str.split(DATE_TIME_SEPARATOR);
  return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
}
 
 
function hostname(str) {
  // https://tools.ietf.org/html/rfc1034#section-3.5
  // https://tools.ietf.org/html/rfc1123#section-2
  return str.length <= 255 && HOSTNAME.test(str);
}
 
 
var NOT_URI_FRAGMENT = /\/|\:/;
function uri(str) {
  // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
  return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
 
 
function regex(str) {
  try {
    new RegExp(str);
    return true;
  } catch(e) {
    return false;
  }
}
 
 
function compareDate(d1, d2) {
  if (!(d1 && d2)) return;
  if (d1 > d2) return 1;
  if (d1 < d2) return -1;
  if (d1 === d2) return 0;
}
 
 
function compareTime(t1, t2) {
  if (!(t1 && t2)) return;
  t1 = t1.match(TIME);
  t2 = t2.match(TIME);
  if (!(t1 && t2)) return;
  t1 = t1[1] + t1[2] + t1[3] + (t1[4]||'');
  t2 = t2[1] + t2[2] + t2[3] + (t2[4]||'');
  if (t1 > t2) return 1;
  if (t1 < t2) return -1;
  if (t1 === t2) return 0;
}
 
 
function compareDateTime(dt1, dt2) {
  if (!(dt1 && dt2)) return;
  dt1 = dt1.split(DATE_TIME_SEPARATOR);
  dt2 = dt2.split(DATE_TIME_SEPARATOR);
  var res = compareDate(dt1[0], dt2[0]);
  if (res === undefined) return;
  return res || compareTime(dt1[1], dt2[1]);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/index.js

Statements: 15.3% (28 / 183)      Branches: 1.04% (1 / 96)      Functions: 0% (0 / 19)      Lines: 16.57% (28 / 169)      Ignored: 1 statement, 1 branch     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392    1         1   1               1           1 1 1     1   1                       1                                                                                 1             1                                                                           1                                                                                                                           1                                                                     1             1         1           1                 1                                     1                                                                                           1                                         1                             1                   1         1         1         1         1                
'use strict';
 
var resolve = require('./resolve')
  , util = require('./util')
  , stableStringify = require('json-stable-stringify')
  , async = require('../async');
 
var beautify;
 
function loadBeautify(){
  if (beautify === undefined) {
    var name = 'js-beautify';
    try { beautify = require(name).js_beautify; }
    catch(e) { beautify = false; }
  }
}
 
var validateGenerator = require('../dotjs/validate');
 
/**
 * Functions below are used inside compiled validations function
 */
 
var co = require('co');
var ucs2length = util.ucs2length;
var equal = require('./equal');
 
// this error is thrown by async schemas to return validation errors via exception
var ValidationError = require('./validation_error');
 
module.exports = compile;
 
 
/**
 * Compiles schema to validation function
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Object} root object with information about the root schema for this schema
 * @param  {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
 * @param  {String} baseId base ID for IDs in the schema
 * @return {Function} validation function
 */
function compile(schema, root, localRefs, baseId) {
  /* jshint validthis: true, evil: true */
  /* eslint no-shadow: 0 */
  var self = this
    , opts = this._opts
    , refVal = [ undefined ]
    , refs = {}
    , patterns = []
    , patternsHash = {}
    , defaults = []
    , defaultsHash = {}
    , customRules = []
    , keepSourceCode = opts.sourceCode !== false;
 
  root = root || { schema: schema, refVal: refVal, refs: refs };
 
  var c = checkCompiling.call(this, schema, root, baseId);
  var compilation = this._compilations[c.index];
  if (c.compiling) return (compilation.callValidate = callValidate);
 
  var formats = this._formats;
  var RULES = this.RULES;
 
  try {
    var v = localCompile(schema, root, localRefs, baseId);
    compilation.validate = v;
    var cv = compilation.callValidate;
    if (cv) {
      cv.schema = v.schema;
      cv.errors = null;
      cv.refs = v.refs;
      cv.refVal = v.refVal;
      cv.root = v.root;
      cv.$async = v.$async;
      if (keepSourceCode) cv.sourceCode = v.sourceCode;
    }
    return v;
  } finally {
    endCompiling.call(this, schema, root, baseId);
  }
 
  function callValidate() {
    var validate = compilation.validate;
    var result = validate.apply(null, arguments);
    callValidate.errors = validate.errors;
    return result;
  }
 
  function localCompile(_schema, _root, localRefs, baseId) {
    var isRoot = !_root || (_root && _root.schema == _schema);
    if (_root.schema != root.schema)
      return compile.call(self, _schema, _root, localRefs, baseId);
 
    var $async = _schema.$async === true;
    if ($async && !opts.transpile) async.setup(opts);
 
    var sourceCode = validateGenerator({
      isTop: true,
      schema: _schema,
      isRoot: isRoot,
      baseId: baseId,
      root: _root,
      schemaPath: '',
      errSchemaPath: '#',
      errorPath: '""',
      RULES: RULES,
      validate: validateGenerator,
      util: util,
      resolve: resolve,
      resolveRef: resolveRef,
      usePattern: usePattern,
      useDefault: useDefault,
      useCustomRule: useCustomRule,
      opts: opts,
      formats: formats,
      self: self
    });
 
    sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
                   + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
                   + sourceCode;
 
    if (opts.beautify) {
      loadBeautify();
      /* istanbul ignore else */
      if (beautify) sourceCode = beautify(sourceCode, opts.beautify);
      else console.error('"npm install js-beautify" to use beautify option');
    }
    // console.log('\n\n\n *** \n', sourceCode);
    var validate, validateCode
      , transpile = opts._transpileFunc;
    try {
      validateCode = $async && transpile
                      ? transpile(sourceCode)
                      : sourceCode;
 
      var makeValidate = new Function(
        'self',
        'RULES',
        'formats',
        'root',
        'refVal',
        'defaults',
        'customRules',
        'co',
        'equal',
        'ucs2length',
        'ValidationError',
        validateCode
      );
 
      validate = makeValidate(
        self,
        RULES,
        formats,
        root,
        refVal,
        defaults,
        customRules,
        co,
        equal,
        ucs2length,
        ValidationError
      );
 
      refVal[0] = validate;
    } catch(e) {
      console.error('Error compiling schema, function code:', validateCode);
      throw e;
    }
 
    validate.schema = _schema;
    validate.errors = null;
    validate.refs = refs;
    validate.refVal = refVal;
    validate.root = isRoot ? validate : _root;
    if ($async) validate.$async = true;
    if (keepSourceCode) validate.sourceCode = sourceCode;
    if (opts.sourceCode === true) {
      validate.source = {
        patterns: patterns,
        defaults: defaults
      };
    }
 
    return validate;
  }
 
  function resolveRef(baseId, ref, isRoot) {
    ref = resolve.url(baseId, ref);
    var refIndex = refs[ref];
    var _refVal, refCode;
    if (refIndex !== undefined) {
      _refVal = refVal[refIndex];
      refCode = 'refVal[' + refIndex + ']';
      return resolvedRef(_refVal, refCode);
    }
    if (!isRoot && root.refs) {
      var rootRefId = root.refs[ref];
      if (rootRefId !== undefined) {
        _refVal = root.refVal[rootRefId];
        refCode = addLocalRef(ref, _refVal);
        return resolvedRef(_refVal, refCode);
      }
    }
 
    refCode = addLocalRef(ref);
    var v = resolve.call(self, localCompile, root, ref);
    if (!v) {
      var localSchema = localRefs && localRefs[ref];
      if (localSchema) {
        v = resolve.inlineRef(localSchema, opts.inlineRefs)
            ? localSchema
            : compile.call(self, localSchema, root, localRefs, baseId);
      }
    }
 
    if (v) {
      replaceLocalRef(ref, v);
      return resolvedRef(v, refCode);
    }
  }
 
  function addLocalRef(ref, v) {
    var refId = refVal.length;
    refVal[refId] = v;
    refs[ref] = refId;
    return 'refVal' + refId;
  }
 
  function replaceLocalRef(ref, v) {
    var refId = refs[ref];
    refVal[refId] = v;
  }
 
  function resolvedRef(refVal, code) {
    return typeof refVal == 'object'
            ? { code: code, schema: refVal, inline: true }
            : { code: code, $async: refVal && refVal.$async };
  }
 
  function usePattern(regexStr) {
    var index = patternsHash[regexStr];
    if (index === undefined) {
      index = patternsHash[regexStr] = patterns.length;
      patterns[index] = regexStr;
    }
    return 'pattern' + index;
  }
 
  function useDefault(value) {
    switch (typeof value) {
      case 'boolean':
      case 'number':
        return '' + value;
      case 'string':
        return util.toQuotedString(value);
      case 'object':
        if (value === null) return 'null';
        var valueStr = stableStringify(value);
        var index = defaultsHash[valueStr];
        if (index === undefined) {
          index = defaultsHash[valueStr] = defaults.length;
          defaults[index] = value;
        }
        return 'default' + index;
    }
  }
 
  function useCustomRule(rule, schema, parentSchema, it) {
    var validateSchema = rule.definition.validateSchema;
    if (validateSchema && self._opts.validateSchema !== false) {
      var valid = validateSchema(schema);
      if (!valid) {
        var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
        if (self._opts.validateSchema == 'log') console.error(message);
        else throw new Error(message);
      }
    }
 
    var compile = rule.definition.compile
      , inline = rule.definition.inline
      , macro = rule.definition.macro;
 
    var validate;
    if (compile) {
      validate = compile.call(self, schema, parentSchema, it);
    } else if (macro) {
      validate = macro.call(self, schema, parentSchema, it);
      if (opts.validateSchema !== false) self.validateSchema(validate, true);
    } else if (inline) {
      validate = inline.call(self, it, rule.keyword, schema, parentSchema);
    } else {
      validate = rule.definition.validate;
    }
 
    var index = customRules.length;
    customRules[index] = validate;
 
    return {
      code: 'customRule' + index,
      validate: validate
    };
  }
}
 
 
/**
 * Checks if the schema is currently compiled
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
 */
function checkCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var index = compIndex.call(this, schema, root, baseId);
  if (index >= 0) return { index: index, compiling: true };
  index = this._compilations.length;
  this._compilations[index] = {
    schema: schema,
    root: root,
    baseId: baseId
  };
  return { index: index, compiling: false };
}
 
 
/**
 * Removes the schema from the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 */
function endCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var i = compIndex.call(this, schema, root, baseId);
  if (i >= 0) this._compilations.splice(i, 1);
}
 
 
/**
 * Index of schema compilation in the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Integer} compilation index
 */
function compIndex(schema, root, baseId) {
  /* jshint validthis: true */
  for (var i=0; i<this._compilations.length; i++) {
    var c = this._compilations[i];
    if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  }
  return -1;
}
 
 
function patternCode(i, patterns) {
  return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
}
 
 
function defaultCode(i) {
  return 'var default' + i + ' = defaults[' + i + '];';
}
 
 
function refValCode(i, refVal) {
  return refVal[i] ? 'var refVal' + i + ' = refVal[' + i + '];' : '';
}
 
 
function customRuleCode(i) {
  return 'var customRule' + i + ' = customRules[' + i + '];';
}
 
 
function vars(arr, statement) {
  if (!arr.length) return '';
  var code = '';
  for (var i=0; i<arr.length; i++)
    code += statement(i, arr);
  return code;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/resolve.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/resolve.js

Statements: 14.37% (24 / 167)      Branches: 0% (0 / 136)      Functions: 0% (0 / 13)      Lines: 16.44% (24 / 146)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269    1         1   1 1 1 1 1 1                   1                                                                                   1                                                               1                         1   1                                                         1                 1             1                                   1                                               1             1           1 1         1             1                 1                                                                  
'use strict';
 
var url = require('url')
  , equal = require('./equal')
  , util = require('./util')
  , SchemaObject = require('./schema_obj');
 
module.exports = resolve;
 
resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;
 
/**
 * [resolve and compile the references ($ref)]
 * @this   Ajv
 * @param  {Function} compile reference to schema compilation funciton (localCompile)
 * @param  {Object} root object with information about the root schema for the current schema
 * @param  {String} ref reference to resolve
 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
 */
function resolve(compile, root, ref) {
  /* jshint validthis: true */
  var refVal = this._refs[ref];
  if (typeof refVal == 'string') {
    if (this._refs[refVal]) refVal = this._refs[refVal];
    else return resolve.call(this, compile, root, refVal);
  }
 
  refVal = refVal || this._schemas[ref];
  if (refVal instanceof SchemaObject) {
    return inlineRef(refVal.schema, this._opts.inlineRefs)
            ? refVal.schema
            : refVal.validate || this._compile(refVal);
  }
 
  var res = resolveSchema.call(this, root, ref);
  var schema, v, baseId;
  if (res) {
    schema = res.schema;
    root = res.root;
    baseId = res.baseId;
  }
 
  if (schema instanceof SchemaObject) {
    v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
  } else if (schema) {
    v = inlineRef(schema, this._opts.inlineRefs)
        ? schema
        : compile.call(this, schema, root, undefined, baseId);
  }
 
  return v;
}
 
 
/**
 * Resolve schema, its root and baseId
 * @this Ajv
 * @param  {Object} root root object with properties schema, refVal, refs
 * @param  {String} ref  reference to resolve
 * @return {Object} object with properties schema, root, baseId
 */
function resolveSchema(root, ref) {
  /* jshint validthis: true */
  var p = url.parse(ref, false, true)
    , refPath = _getFullPath(p)
    , baseId = getFullPath(root.schema.id);
  if (refPath !== baseId) {
    var id = normalizeId(refPath);
    var refVal = this._refs[id];
    if (typeof refVal == 'string') {
      return resolveRecursive.call(this, root, refVal, p);
    } else if (refVal instanceof SchemaObject) {
      if (!refVal.validate) this._compile(refVal);
      root = refVal;
    } else {
      refVal = this._schemas[id];
      if (refVal instanceof SchemaObject) {
        if (!refVal.validate) this._compile(refVal);
        if (id == normalizeId(ref))
          return { schema: refVal, root: root, baseId: baseId };
        root = refVal;
      } else {
        return;
      }
    }
    if (!root.schema) return;
    baseId = getFullPath(root.schema.id);
  }
  return getJsonPointer.call(this, p, baseId, root.schema, root);
}
 
 
/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
  /* jshint validthis: true */
  var res = resolveSchema.call(this, root, ref);
  if (res) {
    var schema = res.schema;
    var baseId = res.baseId;
    root = res.root;
    if (schema.id) baseId = resolveUrl(baseId, schema.id);
    return getJsonPointer.call(this, parsedRef, baseId, schema, root);
  }
}
 
 
var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
  /* jshint validthis: true */
  parsedRef.hash = parsedRef.hash || '';
  if (parsedRef.hash.slice(0,2) != '#/') return;
  var parts = parsedRef.hash.split('/');
 
  for (var i = 1; i < parts.length; i++) {
    var part = parts[i];
    if (part) {
      part = util.unescapeFragment(part);
      schema = schema[part];
      if (!schema) break;
      if (schema.id && !PREVENT_SCOPE_CHANGE[part]) baseId = resolveUrl(baseId, schema.id);
      if (schema.$ref) {
        var $ref = resolveUrl(baseId, schema.$ref);
        var res = resolveSchema.call(this, root, $ref);
        if (res) {
          schema = res.schema;
          root = res.root;
          baseId = res.baseId;
        }
      }
    }
  }
  if (schema && schema != root.schema)
    return { schema: schema, root: root, baseId: baseId };
}
 
 
var SIMPLE_INLINED = util.toHash([
  'type', 'format', 'pattern',
  'maxLength', 'minLength',
  'maxProperties', 'minProperties',
  'maxItems', 'minItems',
  'maximum', 'minimum',
  'uniqueItems', 'multipleOf',
  'required', 'enum'
]);
function inlineRef(schema, limit) {
  if (limit === false) return false;
  if (limit === undefined || limit === true) return checkNoRef(schema);
  else if (limit) return countKeys(schema) <= limit;
}
 
 
function checkNoRef(schema) {
  var item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return false;
      item = schema[key];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  }
  return true;
}
 
 
function countKeys(schema) {
  var count = 0, item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object') count += countKeys(item);
      if (count == Infinity) return Infinity;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return Infinity;
      if (SIMPLE_INLINED[key]) {
        count++;
      } else {
        item = schema[key];
        if (typeof item == 'object') count += countKeys(item) + 1;
        if (count == Infinity) return Infinity;
      }
    }
  }
  return count;
}
 
 
function getFullPath(id, normalize) {
  if (normalize !== false) id = normalizeId(id);
  var p = url.parse(id, false, true);
  return _getFullPath(p);
}
 
 
function _getFullPath(p) {
  var protocolSeparator = p.protocol || p.href.slice(0,2) == '//' ? '//' : '';
  return (p.protocol||'') + protocolSeparator + (p.host||'') + (p.path||'')  + '#';
}
 
 
var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
  return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}
 
 
function resolveUrl(baseId, id) {
  id = normalizeId(id);
  return url.resolve(baseId, id);
}
 
 
/* @this Ajv */
function resolveIds(schema) {
  /* eslint no-shadow: 0 */
  /* jshint validthis: true */
  var id = normalizeId(schema.id);
  var localRefs = {};
  _resolveIds.call(this, schema, getFullPath(id, false), id);
  return localRefs;
 
  /* @this Ajv */
  function _resolveIds(schema, fullPath, baseId) {
    /* jshint validthis: true */
    if (Array.isArray(schema)) {
      for (var i=0; i<schema.length; i++)
        _resolveIds.call(this, schema[i], fullPath+'/'+i, baseId);
    } else if (schema && typeof schema == 'object') {
      if (typeof schema.id == 'string') {
        var id = baseId = baseId
                          ? url.resolve(baseId, schema.id)
                          : schema.id;
        id = normalizeId(id);
 
        var refVal = this._refs[id];
        if (typeof refVal == 'string') refVal = this._refs[refVal];
        if (refVal && refVal.schema) {
          if (!equal(schema, refVal.schema))
            throw new Error('id "' + id + '" resolves to more than one schema');
        } else if (id != normalizeId(fullPath)) {
          if (id[0] == '#') {
            if (localRefs[id] && !equal(schema, localRefs[id]))
              throw new Error('id "' + id + '" resolves to more than one schema');
            localRefs[id] = schema;
          } else {
            this._refs[id] = fullPath;
          }
        }
      }
      for (var key in schema)
        _resolveIds.call(this, schema[key], fullPath+'/'+util.escapeFragment(key), baseId);
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/rules.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/rules.js

Statements: 12.5% (2 / 16)      Branches: 100% (0 / 0)      Functions: 0% (0 / 3)      Lines: 12.5% (2 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42    1     1                                                                        
'use strict';
 
var ruleModules = require('./_rules')
  , toHash = require('./util').toHash;
 
module.exports = function rules() {
  var RULES = [
    { type: 'number',
      rules: [ 'maximum', 'minimum', 'multipleOf'] },
    { type: 'string',
      rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
    { type: 'array',
      rules: [ 'maxItems', 'minItems', 'uniqueItems', 'items' ] },
    { type: 'object',
      rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'properties' ] },
    { rules: [ '$ref', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] }
  ];
 
  var ALL = [ 'type', 'additionalProperties', 'patternProperties' ];
  var KEYWORDS = [ 'additionalItems', '$schema', 'id', 'title', 'description', 'default' ];
  var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  RULES.all = toHash(ALL);
 
  RULES.forEach(function (group) {
    group.rules = group.rules.map(function (keyword) {
      ALL.push(keyword);
      var rule = RULES.all[keyword] = {
        keyword: keyword,
        code: ruleModules[keyword]
      };
      return rule;
    });
  });
 
  RULES.keywords = toHash(ALL.concat(KEYWORDS));
  RULES.types = toHash(TYPES);
  RULES.custom = {};
 
  return RULES;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/schema_obj.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/schema_obj.js

Statements: 75% (3 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 75% (3 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11    1   1   1        
'use strict';
 
var util = require('./util');
 
module.exports = SchemaObject;
 
function SchemaObject(obj) {
  util.copy(obj, this);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/ucs2length.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/ucs2length.js

Statements: 10% (1 / 10)      Branches: 0% (0 / 7)      Functions: 0% (0 / 1)      Lines: 11.11% (1 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22        1                                  
'use strict';
 
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
module.exports = function ucs2length(str) {
  var length = 0
    , len = str.length
    , pos = 0
    , value;
  while (pos < len) {
    length++;
    value = str.charCodeAt(pos++);
    if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos);
      if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
    }
  }
  return length;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/util.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/util.js

Statements: 25.19% (34 / 135)      Branches: 0% (0 / 91)      Functions: 4.55% (1 / 22)      Lines: 28.21% (33 / 117)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259      1                                                   1             1                                     1                                           1 1                                 1 3 25 3       1 1 1                 1                 1             1             1     1             1               1                     1         1         1         1               1               1 1 1                                                                     1           1         1         1         1        
'use strict';
 
 
module.exports = {
  copy: copy,
  checkDataType: checkDataType,
  checkDataTypes: checkDataTypes,
  coerceToTypes: coerceToTypes,
  toHash: toHash,
  getProperty: getProperty,
  escapeQuotes: escapeQuotes,
  ucs2length: require('./ucs2length'),
  varOccurences: varOccurences,
  varReplace: varReplace,
  cleanUpCode: cleanUpCode,
  cleanUpVarErrors: cleanUpVarErrors,
  schemaHasRules: schemaHasRules,
  schemaHasRulesExcept: schemaHasRulesExcept,
  stableStringify: require('json-stable-stringify'),
  toQuotedString: toQuotedString,
  getPathExpr: getPathExpr,
  getPath: getPath,
  getData: getData,
  unescapeFragment: unescapeFragment,
  escapeFragment: escapeFragment,
  escapeJsonPointer: escapeJsonPointer
};
 
 
function copy(o, to) {
  to = to || {};
  for (var key in o) to[key] = o[key];
  return to;
}
 
 
function checkDataType(dataType, data, negate) {
  var EQUAL = negate ? ' !== ' : ' === '
    , AND = negate ? ' || ' : ' && '
    , OK = negate ? '!' : ''
    , NOT = negate ? '' : '!';
  switch (dataType) {
    case 'null': return data + EQUAL + 'null';
    case 'array': return OK + 'Array.isArray(' + data + ')';
    case 'object': return '(' + OK + data + AND +
                          'typeof ' + data + EQUAL + '"object"' + AND +
                          NOT + 'Array.isArray(' + data + '))';
    case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
                           NOT + '(' + data + ' % 1)' +
                           AND + data + EQUAL + data + ')';
    default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
  }
}
 
 
function checkDataTypes(dataTypes, data) {
  switch (dataTypes.length) {
    case 1: return checkDataType(dataTypes[0], data, true);
    default:
      var code = '';
      var types = toHash(dataTypes);
      if (types.array && types.object) {
        code = types.null ? '(': '(!' + data + ' || ';
        code += 'typeof ' + data + ' !== "object")';
        delete types.null;
        delete types.array;
        delete types.object;
      }
      if (types.number) delete types.integer;
      for (var t in types)
        code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
 
      return code;
  }
}
 
 
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
  if (Array.isArray(dataTypes)) {
    var types = [];
    for (var i=0; i<dataTypes.length; i++) {
      var t = dataTypes[i];
      if (COERCE_TO_TYPES[t]) types[types.length] = t;
      else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
    }
    if (types.length) return types;
  } else if (COERCE_TO_TYPES[dataTypes]) {
    return [dataTypes];
  } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
    return ['array'];
  }
}
 
 
function toHash(arr) {
  var hash = {};
  for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
  return hash;
}
 
 
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
  return typeof key == 'number'
          ? '[' + key + ']'
          : IDENTIFIER.test(key)
            ? '.' + key
            : "['" + escapeQuotes(key) + "']";
}
 
 
function escapeQuotes(str) {
  return str.replace(SINGLE_QUOTE, '\\$&')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\f/g, '\\f')
            .replace(/\t/g, '\\t');
}
 
 
function varOccurences(str, dataVar) {
  dataVar += '[^0-9]';
  var matches = str.match(new RegExp(dataVar, 'g'));
  return matches ? matches.length : 0;
}
 
 
function varReplace(str, dataVar, expr) {
  dataVar += '([^0-9])';
  expr = expr.replace(/\$/g, '$$$$');
  return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}
 
 
var EMPTY_ELSE = /else\s*{\s*}/g
  , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
  , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
function cleanUpCode(out) {
  return out.replace(EMPTY_ELSE, '')
            .replace(EMPTY_IF_NO_ELSE, '')
            .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
}
 
 
var ERRORS_REGEXP = /[^v\.]errors/g
  , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
  , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
  , RETURN_VALID = 'return errors === 0;'
  , RETURN_TRUE = 'validate.errors = null; return true;'
  , RETURN_ASYNC = /if \(errors === 0\) return true;\s*else throw new ValidationError\(vErrors\);/
  , RETURN_TRUE_ASYNC = 'return true;';
 
function cleanUpVarErrors(out, async) {
  var matches = out.match(ERRORS_REGEXP);
  if (!matches || matches.length !== 2) return out;
  return async
          ? out.replace(REMOVE_ERRORS_ASYNC, '')
               .replace(RETURN_ASYNC, RETURN_TRUE_ASYNC)
          : out.replace(REMOVE_ERRORS, '')
               .replace(RETURN_VALID, RETURN_TRUE);
}
 
 
function schemaHasRules(schema, rules) {
  for (var key in schema) if (rules[key]) return true;
}
 
 
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
  for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}
 
 
function toQuotedString(str) {
  return '\'' + escapeQuotes(str) + '\'';
}
 
 
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  var path = jsonPointers // false by default
              ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
              : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
  return joinPaths(currentPath, path);
}
 
 
function getPath(currentPath, prop, jsonPointers) {
  var path = jsonPointers // false by default
              ? toQuotedString('/' + escapeJsonPointer(prop))
              : toQuotedString(getProperty(prop));
  return joinPaths(currentPath, path);
}
 
 
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
  var up, jsonPointer, data, matches;
  if ($data === '') return 'rootData';
  if ($data[0] == '/') {
    if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
    jsonPointer = $data;
    data = 'rootData';
  } else {
    matches = $data.match(RELATIVE_JSON_POINTER);
    if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
    up = +matches[1];
    jsonPointer = matches[2];
    if (jsonPointer == '#') {
      if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
      return paths[lvl - up];
    }
 
    if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
    data = 'data' + ((lvl - up) || '');
    if (!jsonPointer) return data;
  }
 
  var expr = data;
  var segments = jsonPointer.split('/');
  for (var i=0; i<segments.length; i++) {
    var segment = segments[i];
    if (segment) {
      data += getProperty(unescapeJsonPointer(segment));
      expr += ' && ' + data;
    }
  }
  return expr;
}
 
 
function joinPaths (a, b) {
  if (a == '""') return b;
  return (a + ' + ' + b).replace(/' \+ '/g, '');
}
 
 
function unescapeFragment(str) {
  return unescapeJsonPointer(decodeURIComponent(str));
}
 
 
function escapeFragment(str) {
  return encodeURIComponent(escapeJsonPointer(str));
}
 
 
function escapeJsonPointer(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
 
 
function unescapeJsonPointer(str) {
  return str.replace(/~1/g, '/').replace(/~0/g, '~');
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/validation_error.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/compile/validation_error.js

Statements: 57.14% (4 / 7)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 57.14% (4 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16    1     1             1 1    
'use strict';
 
module.exports = ValidationError;
 
 
function ValidationError(errors) {
  this.message = 'validation failed';
  this.errors = errors;
  this.ajv = this.validation = true;
}
 
 
ValidationError.prototype = Object.create(Error.prototype);
ValidationError.prototype.constructor = ValidationError;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/

Statements: 4.05% (80 / 1974)      Branches: 4.39% (58 / 1321)      Functions: 0% (0 / 23)      Lines: 4.08% (80 / 1963)      Ignored: 58 statements, 58 branches     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/
File Statements Branches Functions Lines
_limit.js 5.88% (5 / 85) 6.25% (4 / 64) 0% (0 / 1) 5.95% (5 / 84)
_limitItems.js 5.45% (3 / 55) 5.71% (2 / 35) 0% (0 / 1) 5.45% (3 / 55)
_limitLength.js 5.17% (3 / 58) 5.41% (2 / 37) 0% (0 / 1) 5.17% (3 / 58)
_limitProperties.js 5.45% (3 / 55) 5.71% (2 / 35) 0% (0 / 1) 5.45% (3 / 55)
allOf.js 3.13% (1 / 32) 0% (0 / 10) 0% (0 / 1) 3.13% (1 / 32)
anyOf.js 3.85% (2 / 52) 5.56% (1 / 18) 0% (0 / 2) 3.85% (2 / 52)
custom.js 3.25% (5 / 154) 3.54% (4 / 113) 0% (0 / 1) 3.27% (5 / 153)
dependencies.js 3.67% (4 / 109) 5% (3 / 60) 0% (0 / 1) 3.67% (4 / 109)
enum.js 6.25% (3 / 48) 6.45% (2 / 31) 0% (0 / 1) 6.25% (3 / 48)
format.js 2.97% (3 / 101) 2.67% (2 / 75) 0% (0 / 1) 3.06% (3 / 98)
items.js 2.68% (3 / 112) 3.85% (2 / 52) 0% (0 / 1) 2.68% (3 / 112)
multipleOf.js 5.45% (3 / 55) 5.71% (2 / 35) 0% (0 / 1) 5.45% (3 / 55)
not.js 6.06% (4 / 66) 8.33% (3 / 36) 0% (0 / 1) 6.15% (4 / 65)
oneOf.js 5% (3 / 60) 7.69% (2 / 26) 0% (0 / 1) 5% (3 / 60)
pattern.js 5.56% (3 / 54) 5.71% (2 / 35) 0% (0 / 1) 5.56% (3 / 54)
properties.js 2.88% (9 / 312) 3.83% (8 / 209) 0% (0 / 1) 2.89% (9 / 311)
ref.js 3.33% (3 / 90) 3.23% (2 / 62) 0% (0 / 1) 3.37% (3 / 89)
required.js 4.73% (8 / 169) 5.38% (7 / 130) 0% (0 / 1) 4.73% (8 / 169)
uniqueItems.js 5.88% (3 / 51) 5.26% (2 / 38) 0% (0 / 1) 5.88% (3 / 51)
validate.js 3.52% (9 / 256) 2.73% (6 / 220) 0% (0 / 3) 3.56% (9 / 253)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limit.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limit.js

Statements: 5.88% (5 / 85)      Branches: 6.25% (4 / 64)      Functions: 0% (0 / 1)      Lines: 5.95% (5 / 84)      Ignored: 4 statements, 4 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126  1                                                                                           1           1                                                                                                       1           1                            
'use strict';
module.exports = function generate__limit(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $isMax = $keyword == 'maximum',
    $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
    $schemaExcl = it.schema[$exclusiveKeyword],
    $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data,
    $op = $isMax ? '<' : '>',
    $notOp = $isMax ? '>' : '<';
  if ($isDataExcl) {
    var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
      $exclusive = 'exclusive' + $lvl,
      $opExpr = 'op' + $lvl,
      $opStr = '\' + ' + $opExpr + ' + \'';
    out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
    $schemaValueExcl = 'schemaExcl' + $lvl;
    out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { ';
    var $errorKeyword = $exclusiveKeyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else if( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
    }
    out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
  } else {
    var $exclusive = $schemaExcl === true,
      $opStr = $op;
    if (!$exclusive) $opStr += '=';
    var $opExpr = '\'' + $opStr + '\'';
    out += ' if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
    }
    out += ' ' + ($data) + ' ' + ($notOp);
    if ($exclusive) {
      out += '=';
    }
    out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {';
  }
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be ' + ($opStr) + ' ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schema) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limitItems.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limitItems.js

Statements: 5.45% (3 / 55)      Branches: 5.71% (2 / 35)      Functions: 0% (0 / 1)      Lines: 5.45% (3 / 55)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78  1                                                                                                               1           1                            
'use strict';
module.exports = function generate__limitItems(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxItems' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxItems') {
        out += 'more';
      } else {
        out += 'less';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' items\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limitLength.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limitLength.js

Statements: 5.17% (3 / 58)      Branches: 5.41% (2 / 37)      Functions: 0% (0 / 1)      Lines: 5.17% (3 / 58)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83  1                                                                                                                         1           1                            
'use strict';
module.exports = function generate__limitLength(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxLength' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  if (it.opts.unicode === false) {
    out += ' ' + ($data) + '.length ';
  } else {
    out += ' ucs2length(' + ($data) + ') ';
  }
  out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT be ';
      if ($keyword == 'maxLength') {
        out += 'longer';
      } else {
        out += 'shorter';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' characters\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limitProperties.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/_limitProperties.js

Statements: 5.45% (3 / 55)      Branches: 5.71% (2 / 35)      Functions: 0% (0 / 1)      Lines: 5.45% (3 / 55)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78  1                                                                                                               1           1                            
'use strict';
module.exports = function generate__limitProperties(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxProperties' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxProperties') {
        out += 'more';
      } else {
        out += 'less';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' properties\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/allOf.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/allOf.js

Statements: 3.13% (1 / 32)      Branches: 0% (0 / 10)      Functions: 0% (0 / 1)      Lines: 3.13% (1 / 32)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45  1                                                                                      
'use strict';
module.exports = function generate_allOf(it, $keyword) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $allSchemasEmpty = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.util.schemaHasRules($sch, it.RULES.all)) {
        $allSchemasEmpty = false;
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($breakOnError) {
    if ($allSchemasEmpty) {
      out += ' if (true) { ';
    } else {
      out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
    }
  }
  out = it.util.cleanUpCode(out);
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/anyOf.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/anyOf.js

Statements: 3.85% (2 / 52)      Branches: 5.56% (1 / 18)      Functions: 0% (0 / 2)      Lines: 3.85% (2 / 52)      Ignored: 1 statement, 1 branch     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68  1                                                                                                     1                              
'use strict';
module.exports = function generate_anyOf(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $noEmptySchema = $schema.every(function($sch) {
    return it.util.schemaHasRules($sch, it.RULES.all);
  });
  if ($noEmptySchema) {
    var $currentBaseId = $it.baseId;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
        $closingBraces += '}';
      }
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') {  var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match some schema in anyOf\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
    out = it.util.cleanUpCode(out);
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/custom.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/custom.js

Statements: 3.25% (5 / 154)      Branches: 3.54% (4 / 113)      Functions: 0% (0 / 1)      Lines: 3.27% (5 / 153)      Ignored: 4 statements, 4 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223  1                                                                                                                                                                                                                                                                                                 1           1                                                                                 1         1                                                
'use strict';
module.exports = function generate_custom(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $rule = this,
    $definition = 'definition' + $lvl,
    $rDef = $rule.definition,
    $validate = $rDef.validate,
    $compile, $inline, $macro, $ruleValidate, $validateCode;
  if ($isData && $rDef.$data) {
    $validateCode = 'keywordValidate' + $lvl;
    var $validateSchema = $rDef.validateSchema;
    out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
  } else {
    $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
    $schemaValue = 'validate.schema' + $schemaPath;
    $validateCode = $ruleValidate.code;
    $compile = $rDef.compile;
    $inline = $rDef.inline;
    $macro = $rDef.macro;
  }
  var $ruleErrs = $validateCode + '.errors',
    $i = 'i' + $lvl,
    $ruleErr = 'ruleErr' + $lvl,
    $asyncKeyword = $rDef.async;
  if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
  if (!($inline || $macro)) {
    out += '' + ($ruleErrs) + ' = null;';
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($validateSchema) {
    out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') {';
  }
  if ($inline) {
    if ($rDef.statements) {
      out += ' ' + ($ruleValidate.validate) + ' ';
    } else {
      out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
    }
  } else if ($macro) {
    var $it = it.util.copy(it);
    $it.level++;
    var $nextValid = 'valid' + $it.level;
    $it.schema = $ruleValidate.validate;
    $it.schemaPath = '';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($code);
  } else {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    out += '  ' + ($validateCode) + '.call( ';
    if (it.opts.passContext) {
      out += 'this';
    } else {
      out += 'self';
    }
    if ($compile || $rDef.schema === false) {
      out += ' , ' + ($data) + ' ';
    } else {
      out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
    }
    out += ' , (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData )  ';
    var def_callRuleValidate = out;
    out = $$outStack.pop();
    if ($rDef.errors === false) {
      out += ' ' + ($valid) + ' = ';
      if ($asyncKeyword) {
        out += '' + (it.yieldAwait);
      }
      out += '' + (def_callRuleValidate) + '; ';
    } else {
      if ($asyncKeyword) {
        $ruleErrs = 'customErrors' + $lvl;
        out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
      } else {
        out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
      }
    }
  }
  if ($rDef.modifying) {
    out += ' ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
  }
  if ($validateSchema) {
    out += ' }';
  }
  if ($rDef.valid) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  } else {
    out += ' if ( ';
    if ($rDef.valid === undefined) {
      out += ' !';
      if ($macro) {
        out += '' + ($nextValid);
      } else {
        out += '' + ($valid);
      }
    } else {
      out += ' ' + (!$rDef.valid) + ' ';
    }
    out += ') { ';
    $errorKeyword = $rule.keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    var def_customError = out;
    out = $$outStack.pop();
    if ($inline) {
      if ($rDef.errors) {
        if ($rDef.errors != 'full') {
          out += '  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } ';
        }
      } else {
        if ($rDef.errors === false) {
          out += ' ' + (def_customError) + ' ';
        } else {
          out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else {  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } } ';
        }
      }
    } else if ($macro) {
      out += '   var err =   '; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError(vErrors); ';
        } else {
          out += ' validate.errors = vErrors; return false; ';
        }
      }
    } else {
      if ($rDef.errors === false) {
        out += ' ' + (def_customError) + ' ';
      } else {
        out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length;  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + ';  ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '";  ';
        if (it.opts.verbose) {
          out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
        }
        out += ' } } else { ' + (def_customError) + ' } ';
      }
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/dependencies.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/dependencies.js

Statements: 3.67% (4 / 109)      Branches: 5% (3 / 60)      Functions: 0% (0 / 1)      Lines: 3.67% (4 / 109)      Ignored: 3 statements, 3 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150  1                                                                                                                                       1           1                                                                         1                                                                          
'use strict';
module.exports = function generate_dependencies(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $schemaDeps = {},
    $propertyDeps = {};
  for ($property in $schema) {
    var $sch = $schema[$property];
    var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
    $deps[$property] = $sch;
  }
  out += 'var ' + ($errs) + ' = errors;';
  var $currentErrorPath = it.errorPath;
  out += 'var missing' + ($lvl) + ';';
  for (var $property in $propertyDeps) {
    $deps = $propertyDeps[$property];
    out += ' if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
    if ($breakOnError) {
      out += ' && ( ';
      var arr1 = $deps;
      if (arr1) {
        var _$property, $i = -1,
          l1 = arr1.length - 1;
        while ($i < l1) {
          _$property = arr1[$i += 1];
          if ($i) {
            out += ' || ';
          }
          var $prop = it.util.getProperty(_$property);
          out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) ';
        }
      }
      out += ')) {  ';
      var $propertyPath = 'missing' + $lvl,
        $missingProperty = '\' + ' + $propertyPath + ' + \'';
      if (it.opts._errorDataPathProperty) {
        it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should have ';
          if ($deps.length == 1) {
            out += 'property ' + (it.util.escapeQuotes($deps[0]));
          } else {
            out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
          }
          out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
    } else {
      out += ' ) { ';
      var arr2 = $deps;
      if (arr2) {
        var $reqProperty, i2 = -1,
          l2 = arr2.length - 1;
        while (i2 < l2) {
          $reqProperty = arr2[i2 += 1];
          var $prop = it.util.getProperty($reqProperty),
            $missingProperty = it.util.escapeQuotes($reqProperty);
          if (it.opts._errorDataPathProperty) {
            it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers);
          }
          out += ' if (' + ($data) + ($prop) + ' === undefined) {  var err =   '; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ($errorKeyword || 'dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'should have ';
              if ($deps.length == 1) {
                out += 'property ' + (it.util.escapeQuotes($deps[0]));
              } else {
                out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
              }
              out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
        }
      }
    }
    out += ' }   ';
    if ($breakOnError) {
      $closingBraces += '}';
      out += ' else { ';
    }
  }
  it.errorPath = $currentErrorPath;
  var $currentBaseId = $it.baseId;
  for (var $property in $schemaDeps) {
    var $sch = $schemaDeps[$property];
    if (it.util.schemaHasRules($sch, it.RULES.all)) {
      out += ' ' + ($nextValid) + ' = true; if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined) { ';
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + it.util.getProperty($property);
      $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  }
  if ($breakOnError) {
    out += '   ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/enum.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/enum.js

Statements: 6.25% (3 / 48)      Branches: 6.45% (2 / 31)      Functions: 0% (0 / 1)      Lines: 6.25% (3 / 48)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68  1                                                                                           1           1                            
'use strict';
module.exports = function generate_enum(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $i = 'i' + $lvl,
    $vSchema = 'schema' + $lvl;
  if (!$isData) {
    out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ';';
  if ($isData) {
    out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  }
  out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
  if ($isData) {
    out += '  }  ';
  }
  out += ' if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || 'enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to one of the allowed values\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/format.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/format.js

Statements: 2.97% (3 / 101)      Branches: 2.67% (2 / 75)      Functions: 0% (0 / 1)      Lines: 3.06% (3 / 98)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141  1                                                                                                                                                                                                                                             1           1                            
'use strict';
module.exports = function generate_format(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  if (it.opts.format === false) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
    return out;
  }
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $unknownFormats = it.opts.unknownFormats,
    $allowUnknown = Array.isArray($unknownFormats);
  if ($isData) {
    var $format = 'format' + $lvl;
    out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { ';
    if (it.async) {
      out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
    }
    out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if (  ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' (';
    if ($unknownFormats === true || $allowUnknown) {
      out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
      if ($allowUnknown) {
        out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
      }
      out += ') || ';
    }
    out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? ';
    if (it.async) {
      out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
    } else {
      out += ' ' + ($format) + '(' + ($data) + ') ';
    }
    out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
  } else {
    var $format = it.formats[$schema];
    if (!$format) {
      if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) {
        throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
      } else {
        if (!$allowUnknown) {
          console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
          if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information');
        }
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      }
    }
    var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
    if ($isObject) {
      var $async = $format.async === true;
      $format = $format.validate;
    }
    if ($async) {
      if (!it.async) throw new Error('async format in sync schema');
      var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
      out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { ';
    } else {
      out += ' if (! ';
      var $formatRef = 'formats' + it.util.getProperty($schema);
      if ($isObject) $formatRef += '.validate';
      if (typeof $format == 'function') {
        out += ' ' + ($formatRef) + '(' + ($data) + ') ';
      } else {
        out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
      }
      out += ') { ';
    }
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || 'format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match format "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/items.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/items.js

Statements: 2.68% (3 / 112)      Branches: 3.85% (2 / 52)      Functions: 0% (0 / 1)      Lines: 2.68% (3 / 112)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147  1                                                                                 1           1                                                                                                                                                                                                    
'use strict';
module.exports = function generate_items(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId;
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if (Array.isArray($schema)) {
    var $additionalItems = it.schema.additionalItems;
    if ($additionalItems === false) {
      out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
      var $currErrSchemaPath = $errSchemaPath;
      $errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += '  if (!' + ($valid) + ') {   ';
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
      out += ' } ';
      $errSchemaPath = $currErrSchemaPath;
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
          var $passData = $data + '[' + $i + ']';
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + '[' + $i + ']';
          $it.errSchemaPath = $errSchemaPath + '/' + $i;
          $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
          $it.dataPathArr[$dataNxt] = $i;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
    if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
      $it.schema = $additionalItems;
      $it.schemaPath = it.schemaPath + '.additionalItems';
      $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') {  for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + '[' + $idx + ']';
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
      } else {
        out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
      }
      if ($breakOnError) {
        out += ' if (!' + ($nextValid) + ') break; ';
      }
      out += ' } }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  } else if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += '  for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    if ($breakOnError) {
      out += ' if (!' + ($nextValid) + ') break; ';
    }
    out += ' }  ';
    if ($breakOnError) {
      out += ' if (' + ($nextValid) + ') { ';
      $closingBraces += '}';
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/multipleOf.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/multipleOf.js

Statements: 5.45% (3 / 55)      Branches: 5.71% (2 / 35)      Functions: 0% (0 / 1)      Lines: 5.45% (3 / 55)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79  1                                                                                                                 1           1                            
'use strict';
module.exports = function generate_multipleOf(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  out += 'var division' + ($lvl) + ';if (';
  if ($isData) {
    out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
  }
  out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
  if (it.opts.multipleOfPrecision) {
    out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
  } else {
    out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
  }
  out += ' ) ';
  if ($isData) {
    out += '  )  ';
  }
  out += ' ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || 'multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be multiple of ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schema) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/not.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/not.js

Statements: 6.06% (4 / 66)      Branches: 8.33% (3 / 36)      Functions: 0% (0 / 1)      Lines: 6.15% (4 / 65)      Ignored: 3 statements, 3 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86  1                                                                                         1           1                                             1                    
'use strict';
module.exports = function generate_not(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.createErrors = false;
    var $allErrorsOption;
    if ($it.opts.allErrors) {
      $allErrorsOption = $it.opts.allErrors;
      $it.opts.allErrors = false;
    }
    out += ' ' + (it.validate($it)) + ' ';
    $it.createErrors = true;
    if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (' + ($nextValid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
  } else {
    out += '  var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if ($breakOnError) {
      out += ' if (false) { ';
    }
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/oneOf.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/oneOf.js

Statements: 5% (3 / 60)      Branches: 7.69% (2 / 26)      Functions: 0% (0 / 1)      Lines: 5% (3 / 60)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79  1                                                                                                                 1           1                            
'use strict';
module.exports = function generate_oneOf(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;';
  var $currentBaseId = $it.baseId;
  var $wasComposite = it.compositeRule;
  it.compositeRule = $it.compositeRule = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.util.schemaHasRules($sch, it.RULES.all)) {
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
      } else {
        out += ' var ' + ($nextValid) + ' = true; ';
      }
      if ($i) {
        out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { ';
        $closingBraces += '}';
      }
      out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;';
    }
  }
  it.compositeRule = $it.compositeRule = $wasComposite;
  out += '' + ($closingBraces) + 'if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || 'oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match exactly one schema in oneOf\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
  if (it.opts.allErrors) {
    out += ' } ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/pattern.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/pattern.js

Statements: 5.56% (3 / 54)      Branches: 5.71% (2 / 35)      Functions: 0% (0 / 1)      Lines: 5.56% (3 / 54)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77  1                                                                                                             1           1                            
'use strict';
module.exports = function generate_pattern(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
  }
  out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || 'pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match pattern "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/properties.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/properties.js

Statements: 2.88% (9 / 312)      Branches: 3.83% (8 / 209)      Functions: 0% (0 / 1)      Lines: 2.89% (9 / 311)      Ignored: 8 statements, 8 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448  1                                                                                                                                                                                                                             1           1                                                                                                                                                                                                                                               1           1                                                                                                                                                                                                                                                                         1           1                                                               1           1                                                    
'use strict';
module.exports = function generate_properties(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $key = 'key' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt;
  var $schemaKeys = Object.keys($schema || {}),
    $pProperties = it.schema.patternProperties || {},
    $pPropertyKeys = Object.keys($pProperties),
    $aProperties = it.schema.additionalProperties,
    $someProperties = $schemaKeys.length || $pPropertyKeys.length,
    $noAdditional = $aProperties === false,
    $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
    $removeAdditional = it.opts.removeAdditional,
    $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
    $ownProperties = it.opts.ownProperties,
    $currentBaseId = it.baseId;
  var $required = it.schema.required;
  if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
  if (it.opts.v5) {
    var $pgProperties = it.schema.patternGroups || {},
      $pgPropertyKeys = Object.keys($pgProperties);
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
  if ($checkAdditional) {
    out += ' for (var ' + ($key) + ' in ' + ($data) + ') {  ';
    if ($ownProperties) {
      out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
    }
    if ($someProperties) {
      out += ' var isAdditional' + ($lvl) + ' = !(false ';
      if ($schemaKeys.length) {
        if ($schemaKeys.length > 5) {
          out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] ';
        } else {
          var arr1 = $schemaKeys;
          if (arr1) {
            var $propertyKey, i1 = -1,
              l1 = arr1.length - 1;
            while (i1 < l1) {
              $propertyKey = arr1[i1 += 1];
              out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
            }
          }
        }
      }
      if ($pPropertyKeys.length) {
        var arr2 = $pPropertyKeys;
        if (arr2) {
          var $pProperty, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $pProperty = arr2[$i += 1];
            out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
          }
        }
      }
      if (it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length) {
        var arr3 = $pgPropertyKeys;
        if (arr3) {
          var $pgProperty, $i = -1,
            l3 = arr3.length - 1;
          while ($i < l3) {
            $pgProperty = arr3[$i += 1];
            out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') ';
          }
        }
      }
      out += ' ); if (isAdditional' + ($lvl) + ') { ';
    }
    if ($removeAdditional == 'all') {
      out += ' delete ' + ($data) + '[' + ($key) + ']; ';
    } else {
      var $currentErrorPath = it.errorPath;
      var $additionalProperty = '\' + ' + $key + ' + \'';
      if (it.opts._errorDataPathProperty) {
        it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
      }
      if ($noAdditional) {
        if ($removeAdditional) {
          out += ' delete ' + ($data) + '[' + ($key) + ']; ';
        } else {
          out += ' ' + ($nextValid) + ' = false; ';
          var $currErrSchemaPath = $errSchemaPath;
          $errSchemaPath = it.errSchemaPath + '/additionalProperties';
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = ''; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ($errorKeyword || 'additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'should NOT have additional properties\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
            if (it.async) {
              out += ' throw new ValidationError([' + (__err) + ']); ';
            } else {
              out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
          } else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
          }
          $errSchemaPath = $currErrSchemaPath;
          if ($breakOnError) {
            out += ' break; ';
          }
        }
      } else if ($additionalIsSchema) {
        if ($removeAdditional == 'failing') {
          out += ' var ' + ($errs) + ' = errors;  ';
          var $wasComposite = it.compositeRule;
          it.compositeRule = $it.compositeRule = true;
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; }  ';
          it.compositeRule = $it.compositeRule = $wasComposite;
        } else {
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
        }
      }
      it.errorPath = $currentErrorPath;
    }
    if ($someProperties) {
      out += ' } ';
    }
    out += ' }  ';
    if ($breakOnError) {
      out += ' if (' + ($nextValid) + ') { ';
      $closingBraces += '}';
    }
  }
  var $useDefaults = it.opts.useDefaults && !it.compositeRule;
  if ($schemaKeys.length) {
    var arr4 = $schemaKeys;
    if (arr4) {
      var $propertyKey, i4 = -1,
        l4 = arr4.length - 1;
      while (i4 < l4) {
        $propertyKey = arr4[i4 += 1];
        var $sch = $schema[$propertyKey];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          var $prop = it.util.getProperty($propertyKey),
            $passData = $data + $prop,
            $hasDefault = $useDefaults && $sch.default !== undefined;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + $prop;
          $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
          $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
          $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            $code = it.util.varReplace($code, $nextData, $passData);
            var $useData = $passData;
          } else {
            var $useData = $nextData;
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
          }
          if ($hasDefault) {
            out += ' ' + ($code) + ' ';
          } else {
            if ($requiredHash && $requiredHash[$propertyKey]) {
              out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = false; ';
              var $currentErrorPath = it.errorPath,
                $currErrSchemaPath = $errSchemaPath,
                $missingProperty = it.util.escapeQuotes($propertyKey);
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              $errSchemaPath = it.errSchemaPath + '/required';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'';
                  if (it.opts._errorDataPathProperty) {
                    out += 'is a required property';
                  } else {
                    out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              $errSchemaPath = $currErrSchemaPath;
              it.errorPath = $currentErrorPath;
              out += ' } else { ';
            } else {
              if ($breakOnError) {
                out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = true; } else { ';
              } else {
                out += ' if (' + ($useData) + ' !== undefined) { ';
              }
            }
            out += ' ' + ($code) + ' } ';
          }
        }
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  var arr5 = $pPropertyKeys;
  if (arr5) {
    var $pProperty, i5 = -1,
      l5 = arr5.length - 1;
    while (i5 < l5) {
      $pProperty = arr5[i5 += 1];
      var $sch = $pProperties[$pProperty];
      if (it.util.schemaHasRules($sch, it.RULES.all)) {
        $it.schema = $sch;
        $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
        $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
        out += ' for (var ' + ($key) + ' in ' + ($data) + ') {  ';
        if ($ownProperties) {
          out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
        }
        out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
        $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
        var $passData = $data + '[' + $key + ']';
        $it.dataPathArr[$dataNxt] = $key;
        var $code = it.validate($it);
        $it.baseId = $currentBaseId;
        if (it.util.varOccurences($code, $nextData) < 2) {
          out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
        } else {
          out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
        }
        if ($breakOnError) {
          out += ' if (!' + ($nextValid) + ') break; ';
        }
        out += ' } ';
        if ($breakOnError) {
          out += ' else ' + ($nextValid) + ' = true; ';
        }
        out += ' }  ';
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if (it.opts.v5) {
    var arr6 = $pgPropertyKeys;
    if (arr6) {
      var $pgProperty, i6 = -1,
        l6 = arr6.length - 1;
      while (i6 < l6) {
        $pgProperty = arr6[i6 += 1];
        var $pgSchema = $pgProperties[$pgProperty],
          $sch = $pgSchema.schema;
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          $it.schema = $sch;
          $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema';
          $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema';
          out += ' var pgPropCount' + ($lvl) + ' = 0; for (var ' + ($key) + ' in ' + ($data) + ') {  ';
          if ($ownProperties) {
            out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
          }
          out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; ';
          $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
          out += ' } ';
          if ($breakOnError) {
            out += ' else ' + ($nextValid) + ' = true; ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
          var $pgMin = $pgSchema.minimum,
            $pgMax = $pgSchema.maximum;
          if ($pgMin !== undefined || $pgMax !== undefined) {
            out += ' var ' + ($valid) + ' = true; ';
            var $currErrSchemaPath = $errSchemaPath;
            if ($pgMin !== undefined) {
              var $limit = $pgMin,
                $reason = 'minimum',
                $moreOrLess = 'less';
              out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; ';
              $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum';
              out += '  if (!' + ($valid) + ') {   ';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
              if ($pgMax !== undefined) {
                out += ' else ';
              }
            }
            if ($pgMax !== undefined) {
              var $limit = $pgMax,
                $reason = 'maximum',
                $moreOrLess = 'more';
              out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; ';
              $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum';
              out += '  if (!' + ($valid) + ') {   ';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
            }
            $errSchemaPath = $currErrSchemaPath;
            if ($breakOnError) {
              out += ' if (' + ($valid) + ') { ';
              $closingBraces += '}';
            }
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/ref.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/ref.js

Statements: 3.33% (3 / 90)      Branches: 3.23% (2 / 62)      Functions: 0% (0 / 1)      Lines: 3.37% (3 / 89)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122  1                                                                           1           1                                                                                                                                                        
'use strict';
module.exports = function generate_ref(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $async, $refCode;
  if ($schema == '#' || $schema == '#/') {
    if (it.isRoot) {
      $async = it.async;
      $refCode = 'validate';
    } else {
      $async = it.root.schema.$async === true;
      $refCode = 'root.refVal[0]';
    }
  } else {
    var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
    if ($refVal === undefined) {
      var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId;
      if (it.opts.missingRefs == 'fail') {
        console.log($message);
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || '$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        if ($breakOnError) {
          out += ' if (false) { ';
        }
      } else if (it.opts.missingRefs == 'ignore') {
        console.log($message);
        if ($breakOnError) {
          out += ' if (true) { ';
        }
      } else {
        var $error = new Error($message);
        $error.missingRef = it.resolve.url(it.baseId, $schema);
        $error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef));
        throw $error;
      }
    } else if ($refVal.inline) {
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = 'valid' + $it.level;
      $it.schema = $refVal.schema;
      $it.schemaPath = '';
      $it.errSchemaPath = $schema;
      var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
      out += ' ' + ($code) + ' ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
      }
    } else {
      $async = $refVal.$async === true;
      $refCode = $refVal.code;
    }
  }
  if ($refCode) {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    if (it.opts.passContext) {
      out += ' ' + ($refCode) + '.call(this, ';
    } else {
      out += ' ' + ($refCode) + '( ';
    }
    out += ' ' + ($data) + ', (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData)  ';
    var __callValidate = out;
    out = $$outStack.pop();
    if ($async) {
      if (!it.async) throw new Error('async schema referenced by sync schema');
      out += ' try { ';
      if ($breakOnError) {
        out += 'var ' + ($valid) + ' =';
      }
      out += ' ' + (it.yieldAwait) + ' ' + (__callValidate) + '; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } ';
      if ($breakOnError) {
        out += ' if (' + ($valid) + ') { ';
      }
    } else {
      out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
      if ($breakOnError) {
        out += ' else { ';
      }
    }
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/required.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/required.js

Statements: 4.73% (8 / 169)      Branches: 5.38% (7 / 130)      Functions: 0% (0 / 1)      Lines: 4.73% (8 / 169)      Ignored: 7 statements, 7 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252  1                                                                                                                                                                   1           1                                                                                               1           1                                                                           1                                         1                                                                     1                            
'use strict';
module.exports = function generate_required(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $vSchema = 'schema' + $lvl;
  if (!$isData) {
    if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
      var $required = [];
      var arr1 = $schema;
      if (arr1) {
        var $property, i1 = -1,
          l1 = arr1.length - 1;
        while (i1 < l1) {
          $property = arr1[i1 += 1];
          var $propertySch = it.schema.properties[$property];
          if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
            $required[$required.length] = $property;
          }
        }
      }
    } else {
      var $required = $schema;
    }
  }
  if ($isData || $required.length) {
    var $currentErrorPath = it.errorPath,
      $loopRequired = $isData || $required.length >= it.opts.loopRequired;
    if ($breakOnError) {
      out += ' var missing' + ($lvl) + '; ';
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        out += ' var ' + ($valid) + ' = true; ';
        if ($isData) {
          out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined; if (!' + ($valid) + ') break; } ';
        if ($isData) {
          out += '  }  ';
        }
        out += '  if (!' + ($valid) + ') {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      } else {
        out += ' if ( ';
        var arr2 = $required;
        if (arr2) {
          var _$property, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            _$property = arr2[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty(_$property);
            out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) ';
          }
        }
        out += ') {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      }
    } else {
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        if ($isData) {
          out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) {  var err =   '; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is a required property';
              } else {
                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined) {  var err =   '; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
        if ($isData) {
          out += '  }  ';
        }
      } else {
        var arr3 = $required;
        if (arr3) {
          var $reqProperty, i3 = -1,
            l3 = arr3.length - 1;
          while (i3 < l3) {
            $reqProperty = arr3[i3 += 1];
            var $prop = it.util.getProperty($reqProperty),
              $missingProperty = it.util.escapeQuotes($reqProperty);
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers);
            }
            out += ' if (' + ($data) + ($prop) + ' === undefined) {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'';
                if (it.opts._errorDataPathProperty) {
                  out += 'is a required property';
                } else {
                  out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                }
                out += '\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
    }
    it.errorPath = $currentErrorPath;
  } else if ($breakOnError) {
    out += ' if (true) {';
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/uniqueItems.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/uniqueItems.js

Statements: 5.88% (3 / 51)      Branches: 5.26% (2 / 38)      Functions: 0% (0 / 1)      Lines: 5.88% (3 / 51)      Ignored: 2 statements, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74  1                                                                                             1           1                                      
'use strict';
module.exports = function generate_uniqueItems(it, $keyword) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.v5 && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (($schema || $isData) && it.opts.uniqueItems !== false) {
    if ($isData) {
      out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
    }
    out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } ';
    if ($isData) {
      out += '  }  ';
    }
    out += ' if (!' + ($valid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema:  ';
        if ($isData) {
          out += 'validate.schema' + ($schemaPath);
        } else {
          out += '' + ($schema);
        }
        out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/validate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/lib/dotjs/validate.js

Statements: 3.52% (9 / 256)      Branches: 2.73% (6 / 220)      Functions: 0% (0 / 3)      Lines: 3.56% (9 / 253)      Ignored: 6 statements, 6 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378  1                                                                                                                                                                                                                                             1           1                                                                                                                                                                                                                                                                                                 1           1                                                                                                           1           1                                                         1         1            
'use strict';
module.exports = function generate_validate(it, $keyword) {
  var out = '';
  var $async = it.schema.$async === true;
  if (it.isTop) {
    var $top = it.isTop,
      $lvl = it.level = 0,
      $dataLvl = it.dataLevel = 0,
      $data = 'data';
    it.rootId = it.resolve.fullPath(it.root.schema.id);
    it.baseId = it.baseId || it.rootId;
    if ($async) {
      it.async = true;
      var $es7 = it.opts.async == 'es7';
      it.yieldAwait = $es7 ? 'await' : 'yield';
    }
    delete it.isTop;
    it.dataPathArr = [undefined];
    out += ' var validate = ';
    if ($async) {
      if ($es7) {
        out += ' (async function ';
      } else {
        if (it.opts.async == 'co*') {
          out += 'co.wrap';
        }
        out += '(function* ';
      }
    } else {
      out += ' (function ';
    }
    out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; var vErrors = null; ';
    out += ' var errors = 0;     ';
    out += ' if (rootData === undefined) rootData = data;';
  } else {
    var $lvl = it.level,
      $dataLvl = it.dataLevel,
      $data = 'data' + ($dataLvl || '');
    if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id);
    if ($async && !it.async) throw new Error('async schema in sync schema');
    out += ' var errs_' + ($lvl) + ' = errors;';
  }
  var $valid = 'valid' + $lvl,
    $breakOnError = !it.opts.allErrors,
    $closingBraces1 = '',
    $closingBraces2 = '',
    $errorKeyword;
  var $typeSchema = it.schema.type,
    $typeIsArray = Array.isArray($typeSchema);
  if ($typeSchema && it.opts.coerceTypes) {
    var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
    if ($coerceToTypes) {
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type',
        $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
      out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') {  ';
      var $dataType = 'dataType' + $lvl,
        $coerced = 'coerced' + $lvl;
      out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
      if (it.opts.coerceTypes == 'array') {
        out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
      }
      out += ' var ' + ($coerced) + ' = undefined; ';
      var $bracesCoercion = '';
      var arr1 = $coerceToTypes;
      if (arr1) {
        var $type, $i = -1,
          l1 = arr1.length - 1;
        while ($i < l1) {
          $type = arr1[$i += 1];
          if ($i) {
            out += ' if (' + ($coerced) + ' === undefined) { ';
            $bracesCoercion += '}';
          }
          if (it.opts.coerceTypes == 'array' && $type != 'array') {
            out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + ';  } ';
          }
          if ($type == 'string') {
            out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
          } else if ($type == 'number' || $type == 'integer') {
            out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
            if ($type == 'integer') {
              out += ' && !(' + ($data) + ' % 1)';
            }
            out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
          } else if ($type == 'boolean') {
            out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
          } else if ($type == 'null') {
            out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
          } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
            out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
          }
        }
      }
      out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) {   ';
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
        if ($typeIsArray) {
          out += '' + ($typeSchema.join(","));
        } else {
          out += '' + ($typeSchema);
        }
        out += '\' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should be ';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
      out += ' } else {  ';
      var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
        $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
      out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
      if (!$dataLvl) {
        out += 'if (' + ($parentData) + ' !== undefined)';
      }
      out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } ';
    }
  }
  var $refKeywords;
  if (it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'))) {
    if (it.opts.extendRefs == 'fail') {
      throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"');
    } else if (it.opts.extendRefs == 'ignore') {
      $refKeywords = false;
      console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
    } else if (it.opts.extendRefs !== true) {
      console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour');
    }
  }
  if (it.schema.$ref && !$refKeywords) {
    out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
    if ($breakOnError) {
      out += ' } if (errors === ';
      if ($top) {
        out += '0';
      } else {
        out += 'errs_' + ($lvl);
      }
      out += ') { ';
      $closingBraces2 += '}';
    }
  } else {
    var arr2 = it.RULES;
    if (arr2) {
      var $rulesGroup, i2 = -1,
        l2 = arr2.length - 1;
      while (i2 < l2) {
        $rulesGroup = arr2[i2 += 1];
        if ($shouldUseGroup($rulesGroup)) {
          if ($rulesGroup.type) {
            out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
          }
          if (it.opts.useDefaults && !it.compositeRule) {
            if ($rulesGroup.type == 'object' && it.schema.properties) {
              var $schema = it.schema.properties,
                $schemaKeys = Object.keys($schema);
              var arr3 = $schemaKeys;
              if (arr3) {
                var $propertyKey, i3 = -1,
                  l3 = arr3.length - 1;
                while (i3 < l3) {
                  $propertyKey = arr3[i3 += 1];
                  var $sch = $schema[$propertyKey];
                  if ($sch.default !== undefined) {
                    var $passData = $data + it.util.getProperty($propertyKey);
                    out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
                    if (it.opts.useDefaults == 'shared') {
                      out += ' ' + (it.useDefault($sch.default)) + ' ';
                    } else {
                      out += ' ' + (JSON.stringify($sch.default)) + ' ';
                    }
                    out += '; ';
                  }
                }
              }
            } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
              var arr4 = it.schema.items;
              if (arr4) {
                var $sch, $i = -1,
                  l4 = arr4.length - 1;
                while ($i < l4) {
                  $sch = arr4[$i += 1];
                  if ($sch.default !== undefined) {
                    var $passData = $data + '[' + $i + ']';
                    out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
                    if (it.opts.useDefaults == 'shared') {
                      out += ' ' + (it.useDefault($sch.default)) + ' ';
                    } else {
                      out += ' ' + (JSON.stringify($sch.default)) + ' ';
                    }
                    out += '; ';
                  }
                }
              }
            }
          }
          var arr5 = $rulesGroup.rules;
          if (arr5) {
            var $rule, i5 = -1,
              l5 = arr5.length - 1;
            while (i5 < l5) {
              $rule = arr5[i5 += 1];
              if ($shouldUseRule($rule)) {
                out += ' ' + ($rule.code(it, $rule.keyword)) + ' ';
                if ($breakOnError) {
                  $closingBraces1 += '}';
                }
              }
            }
          }
          if ($breakOnError) {
            out += ' ' + ($closingBraces1) + ' ';
            $closingBraces1 = '';
          }
          if ($rulesGroup.type) {
            out += ' } ';
            if ($typeSchema && $typeSchema === $rulesGroup.type) {
              var $typeChecked = true;
              out += ' else { ';
              var $schemaPath = it.schemaPath + '.type',
                $errSchemaPath = it.errSchemaPath + '/type';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                if ($typeIsArray) {
                  out += '' + ($typeSchema.join(","));
                } else {
                  out += '' + ($typeSchema);
                }
                out += '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should be ';
                  if ($typeIsArray) {
                    out += '' + ($typeSchema.join(","));
                  } else {
                    out += '' + ($typeSchema);
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
            }
          }
          if ($breakOnError) {
            out += ' if (errors === ';
            if ($top) {
              out += '0';
            } else {
              out += 'errs_' + ($lvl);
            }
            out += ') { ';
            $closingBraces2 += '}';
          }
        }
      }
    }
  }
  if ($typeSchema && !$typeChecked && !(it.opts.coerceTypes && $coerceToTypes)) {
    var $schemaPath = it.schemaPath + '.type',
      $errSchemaPath = it.errSchemaPath + '/type',
      $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
    out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
      if ($typeIsArray) {
        out += '' + ($typeSchema.join(","));
      } else {
        out += '' + ($typeSchema);
      }
      out += '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should be ';
        if ($typeIsArray) {
          out += '' + ($typeSchema.join(","));
        } else {
          out += '' + ($typeSchema);
        }
        out += '\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces2) + ' ';
  }
  if ($top) {
    if ($async) {
      out += ' if (errors === 0) return true;           ';
      out += ' else throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; ';
      out += ' return errors === 0;       ';
    }
    out += ' }); return validate;';
  } else {
    out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
  }
  out = it.util.cleanUpCode(out);
  if ($top && $breakOnError) {
    out = it.util.cleanUpVarErrors(out, $async);
  }
 
  function $shouldUseGroup($rulesGroup) {
    for (var i = 0; i < $rulesGroup.rules.length; i++)
      if ($shouldUseRule($rulesGroup.rules[i])) return true;
  }
 
  function $shouldUseRule($rule) {
    return it.schema[$rule.keyword] !== undefined || ($rule.keyword == 'properties' && (it.schema.additionalProperties === false || typeof it.schema.additionalProperties == 'object' || (it.schema.patternProperties && Object.keys(it.schema.patternProperties).length) || (it.opts.v5 && it.schema.patternGroups && Object.keys(it.schema.patternGroups).length)));
  }
  return out;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/co/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/co/

Statements: 19.1% (17 / 89)      Branches: 0% (0 / 42)      Functions: 0% (0 / 20)      Lines: 22.97% (17 / 74)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/co/
File Statements Branches Functions Lines
index.js 19.1% (17 / 89) 0% (0 / 42) 0% (0 / 20) 22.97% (17 / 74)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/co/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/co/index.js

Statements: 19.1% (17 / 89)      Branches: 0% (0 / 42)      Functions: 0% (0 / 20)      Lines: 22.97% (17 / 74)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239          1           1                           1     1                           1                                     1                               1                                     1                                   1                                   1                                       1                         1                           1                                 1                       1                     1                             1        
 
/**
 * slice() reference.
 */
 
var slice = Array.prototype.slice;
 
/**
 * Expose `co`.
 */
 
module.exports = co['default'] = co.co = co;
 
/**
 * Wrap the given generator `fn` into a
 * function that returns a promise.
 * This is a separate function so that
 * every `co()` call doesn't create a new,
 * unnecessary closure.
 *
 * @param {GeneratorFunction} fn
 * @return {Function}
 * @api public
 */
 
co.wrap = function (fn) {
  createPromise.__generatorFunction__ = fn;
  return createPromise;
  function createPromise() {
    return co.call(this, fn.apply(this, arguments));
  }
};
 
/**
 * Execute the generator function or a generator
 * and return a promise.
 *
 * @param {Function} fn
 * @return {Promise}
 * @api public
 */
 
function co(gen) {
  var ctx = this;
  var args = slice.call(arguments, 1)
 
  // we wrap everything in a promise to avoid promise chaining,
  // which leads to memory leak errors.
  // see https://github.com/tj/co/issues/180
  return new Promise(function(resolve, reject) {
    if (typeof gen === 'function') gen = gen.apply(ctx, args);
    if (!gen || typeof gen.next !== 'function') return resolve(gen);
 
    onFulfilled();
 
    /**
     * @param {Mixed} res
     * @return {Promise}
     * @api private
     */
 
    function onFulfilled(res) {
      var ret;
      try {
        ret = gen.next(res);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }
 
    /**
     * @param {Error} err
     * @return {Promise}
     * @api private
     */
 
    function onRejected(err) {
      var ret;
      try {
        ret = gen.throw(err);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }
 
    /**
     * Get the next value in the generator,
     * return a promise.
     *
     * @param {Object} ret
     * @return {Promise}
     * @api private
     */
 
    function next(ret) {
      if (ret.done) return resolve(ret.value);
      var value = toPromise.call(ctx, ret.value);
      if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
      return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
        + 'but the following object was passed: "' + String(ret.value) + '"'));
    }
  });
}
 
/**
 * Convert a `yield`ed value into a promise.
 *
 * @param {Mixed} obj
 * @return {Promise}
 * @api private
 */
 
function toPromise(obj) {
  if (!obj) return obj;
  if (isPromise(obj)) return obj;
  if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
  if ('function' == typeof obj) return thunkToPromise.call(this, obj);
  if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
  if (isObject(obj)) return objectToPromise.call(this, obj);
  return obj;
}
 
/**
 * Convert a thunk to a promise.
 *
 * @param {Function}
 * @return {Promise}
 * @api private
 */
 
function thunkToPromise(fn) {
  var ctx = this;
  return new Promise(function (resolve, reject) {
    fn.call(ctx, function (err, res) {
      if (err) return reject(err);
      if (arguments.length > 2) res = slice.call(arguments, 1);
      resolve(res);
    });
  });
}
 
/**
 * Convert an array of "yieldables" to a promise.
 * Uses `Promise.all()` internally.
 *
 * @param {Array} obj
 * @return {Promise}
 * @api private
 */
 
function arrayToPromise(obj) {
  return Promise.all(obj.map(toPromise, this));
}
 
/**
 * Convert an object of "yieldables" to a promise.
 * Uses `Promise.all()` internally.
 *
 * @param {Object} obj
 * @return {Promise}
 * @api private
 */
 
function objectToPromise(obj){
  var results = new obj.constructor();
  var keys = Object.keys(obj);
  var promises = [];
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var promise = toPromise.call(this, obj[key]);
    if (promise && isPromise(promise)) defer(promise, key);
    else results[key] = obj[key];
  }
  return Promise.all(promises).then(function () {
    return results;
  });
 
  function defer(promise, key) {
    // predefine the key in the result
    results[key] = undefined;
    promises.push(promise.then(function (res) {
      results[key] = res;
    }));
  }
}
 
/**
 * Check if `obj` is a promise.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */
 
function isPromise(obj) {
  return 'function' == typeof obj.then;
}
 
/**
 * Check if `obj` is a generator.
 *
 * @param {Mixed} obj
 * @return {Boolean}
 * @api private
 */
 
function isGenerator(obj) {
  return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}
 
/**
 * Check if `obj` is a generator function.
 *
 * @param {Mixed} obj
 * @return {Boolean}
 * @api private
 */
function isGeneratorFunction(obj) {
  var constructor = obj.constructor;
  if (!constructor) return false;
  if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
  return isGenerator(constructor.prototype);
}
 
/**
 * Check for plain object.
 *
 * @param {Mixed} val
 * @return {Boolean}
 * @api private
 */
 
function isObject(val) {
  return Object == val.constructor;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/json-stable-stringify/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/json-stable-stringify/

Statements: 6.56% (4 / 61)      Branches: 5.88% (3 / 51)      Functions: 0% (0 / 9)      Lines: 7.55% (4 / 53)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/json-stable-stringify/
File Statements Branches Functions Lines
index.js 6.56% (4 / 61) 5.88% (3 / 51) 0% (0 / 9) 7.55% (4 / 53)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/json-stable-stringify/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/json-stable-stringify/index.js

Statements: 6.56% (4 / 61)      Branches: 5.88% (3 / 51)      Functions: 0% (0 / 9)      Lines: 7.55% (4 / 53)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 861   1                                                                                                                                           1       1                  
var json = typeof JSON !== 'undefined' ? JSON : require('jsonify');
 
module.exports = function (obj, opts) {
    if (!opts) opts = {};
    if (typeof opts === 'function') opts = { cmp: opts };
    var space = opts.space || '';
    if (typeof space === 'number') space = Array(space+1).join(' ');
    var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
    var replacer = opts.replacer || function(key, value) { return value; };
 
    var cmp = opts.cmp && (function (f) {
        return function (node) {
            return function (a, b) {
                var aobj = { key: a, value: node[a] };
                var bobj = { key: b, value: node[b] };
                return f(aobj, bobj);
            };
        };
    })(opts.cmp);
 
    var seen = [];
    return (function stringify (parent, key, node, level) {
        var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
        var colonSeparator = space ? ': ' : ':';
 
        if (node && node.toJSON && typeof node.toJSON === 'function') {
            node = node.toJSON();
        }
 
        node = replacer.call(parent, key, node);
 
        if (node === undefined) {
            return;
        }
        if (typeof node !== 'object' || node === null) {
            return json.stringify(node);
        }
        if (isArray(node)) {
            var out = [];
            for (var i = 0; i < node.length; i++) {
                var item = stringify(node, i, node[i], level+1) || json.stringify(null);
                out.push(indent + space + item);
            }
            return '[' + out.join(',') + indent + ']';
        }
        else {
            if (seen.indexOf(node) !== -1) {
                if (cycles) return json.stringify('__cycle__');
                throw new TypeError('Converting circular structure to JSON');
            }
            else seen.push(node);
 
            var keys = objectKeys(node).sort(cmp && cmp(node));
            var out = [];
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var value = stringify(node, key, node[key], level+1);
 
                if(!value) continue;
 
                var keyValue = json.stringify(key)
                    + colonSeparator
                    + value;
                ;
                out.push(indent + space + keyValue);
            }
            seen.splice(seen.indexOf(node), 1);
            return '{' + out.join(',') + indent + '}';
        }
    })({ '': obj }, '', obj, 0);
};
 
var isArray = Array.isArray || function (x) {
    return {}.toString.call(x) === '[object Array]';
};
 
var objectKeys = Object.keys || function (obj) {
    var has = Object.prototype.hasOwnProperty || function () { return true };
    var keys = [];
    for (var key in obj) {
        if (has.call(obj, key)) keys.push(key);
    }
    return keys;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/har-schema/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/har-schema/lib/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/har-schema/lib/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/har-schema/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/har-schema/lib/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24    1                                          
'use strict'
 
module.exports = {
  afterRequest: require('./afterRequest.json'),
  beforeRequest: require('./beforeRequest.json'),
  browser: require('./browser.json'),
  cache: require('./cache.json'),
  content: require('./content.json'),
  cookie: require('./cookie.json'),
  creator: require('./creator.json'),
  entry: require('./entry.json'),
  har: require('./har.json'),
  header: require('./header.json'),
  log: require('./log.json'),
  page: require('./page.json'),
  pageTimings: require('./pageTimings.json'),
  postData: require('./postData.json'),
  query: require('./query.json'),
  request: require('./request.json'),
  response: require('./response.json'),
  timings: require('./timings.json')
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/

Statements: 16.67% (59 / 354)      Branches: 0% (0 / 332)      Functions: 0% (0 / 32)      Lines: 16.67% (59 / 354)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/
File Statements Branches Functions Lines
client.js 11.49% (10 / 87) 0% (0 / 120) 0% (0 / 4) 11.49% (10 / 87)
crypto.js 30.23% (13 / 43) 0% (0 / 18) 0% (0 / 7) 30.23% (13 / 43)
index.js 100% (7 / 7) 100% (0 / 0) 100% (0 / 0) 100% (7 / 7)
server.js 9.66% (14 / 145) 0% (0 / 140) 0% (0 / 12) 9.66% (14 / 145)
utils.js 20.83% (15 / 72) 0% (0 / 54) 0% (0 / 9) 20.83% (15 / 72)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/client.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/client.js

Statements: 11.49% (10 / 87)      Branches: 0% (0 / 120)      Functions: 0% (0 / 4)      Lines: 11.49% (10 / 87)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371    1 1 1 1 1         1                                                               1                                                                                                                                                                                                             1                                                                                                                                                                   1                                                                                                                                                                       1                                                                                                                    
// Load modules
 
var Url = require('url');
var Hoek = require('hoek');
var Cryptiles = require('cryptiles');
var Crypto = require('./crypto');
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {};
 
 
// Generate an Authorization header for a given request
 
/*
    uri: 'http://example.com/resource?a=b' or object from Url.parse()
    method: HTTP verb (e.g. 'GET', 'POST')
    options: {
 
        // Required
 
        credentials: {
            id: 'dh37fgj492je',
            key: 'aoijedoaijsdlaksjdl',
            algorithm: 'sha256'                                 // 'sha1', 'sha256'
        },
 
        // Optional
 
        ext: 'application-specific',                        // Application specific data sent via the ext attribute
        timestamp: Date.now(),                              // A pre-calculated timestamp
        nonce: '2334f34f',                                  // A pre-generated nonce
        localtimeOffsetMsec: 400,                           // Time offset to sync with server time (ignored if timestamp provided)
        payload: '{"some":"payload"}',                      // UTF-8 encoded string for body hash generation (ignored if hash provided)
        contentType: 'application/json',                    // Payload content-type (ignored if hash provided)
        hash: 'U4MKKSmiVxk37JCCrAVIjV=',                    // Pre-calculated payload hash
        app: '24s23423f34dx',                               // Oz application id
        dlg: '234sz34tww3sd'                                // Oz delegated-by application id
    }
*/
 
exports.header = function (uri, method, options) {
 
    var result = {
        field: '',
        artifacts: {}
    };
 
    // Validate inputs
 
    if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') ||
        !method || typeof method !== 'string' ||
        !options || typeof options !== 'object') {
 
        result.err = 'Invalid argument type';
        return result;
    }
 
    // Application time
 
    var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
 
    // Validate credentials
 
    var credentials = options.credentials;
    if (!credentials ||
        !credentials.id ||
        !credentials.key ||
        !credentials.algorithm) {
 
        result.err = 'Invalid credential object';
        return result;
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        result.err = 'Unknown algorithm';
        return result;
    }
 
    // Parse URI
 
    if (typeof uri === 'string') {
        uri = Url.parse(uri);
    }
 
    // Calculate signature
 
    var artifacts = {
        ts: timestamp,
        nonce: options.nonce || Cryptiles.randomString(6),
        method: method,
        resource: uri.pathname + (uri.search || ''),                            // Maintain trailing '?'
        host: uri.hostname,
        port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
        hash: options.hash,
        ext: options.ext,
        app: options.app,
        dlg: options.dlg
    };
 
    result.artifacts = artifacts;
 
    // Calculate payload hash
 
    if (!artifacts.hash &&
        (options.payload || options.payload === '')) {
 
        artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
    }
 
    var mac = Crypto.calculateMac('header', credentials, artifacts);
 
    // Construct header
 
    var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '';       // Other falsey values allowed
    var header = 'Hawk id="' + credentials.id +
                 '", ts="' + artifacts.ts +
                 '", nonce="' + artifacts.nonce +
                 (artifacts.hash ? '", hash="' + artifacts.hash : '') +
                 (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') +
                 '", mac="' + mac + '"';
 
    if (artifacts.app) {
        header += ', app="' + artifacts.app +
                  (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
    }
 
    result.field = header;
 
    return result;
};
 
 
// Validate server response
 
/*
    res:        node's response object
    artifacts:  object received from header().artifacts
    options: {
        payload:    optional payload received
        required:   specifies if a Server-Authorization header is required. Defaults to 'false'
    }
*/
 
exports.authenticate = function (res, credentials, artifacts, options) {
 
    artifacts = Hoek.clone(artifacts);
    options = options || {};
 
    if (res.headers['www-authenticate']) {
 
        // Parse HTTP WWW-Authenticate header
 
        var wwwAttributes = Utils.parseAuthorizationHeader(res.headers['www-authenticate'], ['ts', 'tsm', 'error']);
        if (wwwAttributes instanceof Error) {
            return false;
        }
 
        // Validate server timestamp (not used to update clock since it is done via the SNPT client)
 
        if (wwwAttributes.ts) {
            var tsm = Crypto.calculateTsMac(wwwAttributes.ts, credentials);
            if (tsm !== wwwAttributes.tsm) {
                return false;
            }
        }
    }
 
    // Parse HTTP Server-Authorization header
 
    if (!res.headers['server-authorization'] &&
        !options.required) {
 
        return true;
    }
 
    var attributes = Utils.parseAuthorizationHeader(res.headers['server-authorization'], ['mac', 'ext', 'hash']);
    if (attributes instanceof Error) {
        return false;
    }
 
    artifacts.ext = attributes.ext;
    artifacts.hash = attributes.hash;
 
    var mac = Crypto.calculateMac('response', credentials, artifacts);
    if (mac !== attributes.mac) {
        return false;
    }
 
    if (!options.payload &&
        options.payload !== '') {
 
        return true;
    }
 
    if (!attributes.hash) {
        return false;
    }
 
    var calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers['content-type']);
    return (calculatedHash === attributes.hash);
};
 
 
// Generate a bewit value for a given URI
 
/*
    uri: 'http://example.com/resource?a=b' or object from Url.parse()
    options: {
 
        // Required
 
        credentials: {
            id: 'dh37fgj492je',
            key: 'aoijedoaijsdlaksjdl',
            algorithm: 'sha256'                             // 'sha1', 'sha256'
        },
        ttlSec: 60 * 60,                                    // TTL in seconds
 
        // Optional
 
        ext: 'application-specific',                        // Application specific data sent via the ext attribute
        localtimeOffsetMsec: 400                            // Time offset to sync with server time
    };
*/
 
exports.getBewit = function (uri, options) {
 
    // Validate inputs
 
    if (!uri ||
        (typeof uri !== 'string' && typeof uri !== 'object') ||
        !options ||
        typeof options !== 'object' ||
        !options.ttlSec) {
 
        return '';
    }
 
    options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext);       // Zero is valid value
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);
 
    // Validate credentials
 
    var credentials = options.credentials;
    if (!credentials ||
        !credentials.id ||
        !credentials.key ||
        !credentials.algorithm) {
 
        return '';
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        return '';
    }
 
    // Parse URI
 
    if (typeof uri === 'string') {
        uri = Url.parse(uri);
    }
 
    // Calculate signature
 
    var exp = Math.floor(now / 1000) + options.ttlSec;
    var mac = Crypto.calculateMac('bewit', credentials, {
        ts: exp,
        nonce: '',
        method: 'GET',
        resource: uri.pathname + (uri.search || ''),                            // Maintain trailing '?'
        host: uri.hostname,
        port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
        ext: options.ext
    });
 
    // Construct bewit: id\exp\mac\ext
 
    var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
    return Hoek.base64urlEncode(bewit);
};
 
 
// Generate an authorization string for a message
 
/*
    host: 'example.com',
    port: 8000,
    message: '{"some":"payload"}',                          // UTF-8 encoded string for body hash generation
    options: {
 
        // Required
 
        credentials: {
            id: 'dh37fgj492je',
            key: 'aoijedoaijsdlaksjdl',
            algorithm: 'sha256'                             // 'sha1', 'sha256'
        },
 
        // Optional
 
        timestamp: Date.now(),                              // A pre-calculated timestamp
        nonce: '2334f34f',                                  // A pre-generated nonce
        localtimeOffsetMsec: 400,                           // Time offset to sync with server time (ignored if timestamp provided)
    }
*/
 
exports.message = function (host, port, message, options) {
 
    // Validate inputs
 
    if (!host || typeof host !== 'string' ||
        !port || typeof port !== 'number' ||
        message === null || message === undefined || typeof message !== 'string' ||
        !options || typeof options !== 'object') {
 
        return null;
    }
 
    // Application time
 
    var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
 
    // Validate credentials
 
    var credentials = options.credentials;
    if (!credentials ||
        !credentials.id ||
        !credentials.key ||
        !credentials.algorithm) {
 
        // Invalid credential object
        return null;
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        return null;
    }
 
    // Calculate signature
 
    var artifacts = {
        ts: timestamp,
        nonce: options.nonce || Cryptiles.randomString(6),
        host: host,
        port: port,
        hash: Crypto.calculatePayloadHash(message, credentials.algorithm)
    };
 
    // Construct authorization
 
    var result = {
        id: credentials.id,
        ts: artifacts.ts,
        nonce: artifacts.nonce,
        hash: artifacts.hash,
        mac: Crypto.calculateMac('message', credentials, artifacts)
    };
 
    return result;
};
 
 
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/crypto.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/crypto.js

Statements: 30.23% (13 / 43)      Branches: 0% (0 / 18)      Functions: 0% (0 / 7)      Lines: 30.23% (13 / 43)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128    1 1 1         1         1         1                                                 1                   1                                                                   1               1                 1             1               1              
// Load modules
 
var Crypto = require('crypto');
var Url = require('url');
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {};
 
 
// MAC normalization format version
 
exports.headerVersion = '1';                        // Prevent comparison of mac values generated with different normalized string formats
 
 
// Supported HMAC algorithms
 
exports.algorithms = ['sha1', 'sha256'];
 
 
// Calculate the request MAC
 
/*
    type: 'header',                                 // 'header', 'bewit', 'response'
    credentials: {
        key: 'aoijedoaijsdlaksjdl',
        algorithm: 'sha256'                         // 'sha1', 'sha256'
    },
    options: {
        method: 'GET',
        resource: '/resource?a=1&b=2',
        host: 'example.com',
        port: 8080,
        ts: 1357718381034,
        nonce: 'd3d345f',
        hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=',
        ext: 'app-specific-data',
        app: 'hf48hd83qwkj',                        // Application id (Oz)
        dlg: 'd8djwekds9cj'                         // Delegated by application id (Oz), requires options.app
    }
*/
 
exports.calculateMac = function (type, credentials, options) {
 
    var normalized = exports.generateNormalizedString(type, options);
 
    var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized);
    var digest = hmac.digest('base64');
    return digest;
};
 
 
exports.generateNormalizedString = function (type, options) {
 
    var resource = options.resource || '';
    if (resource &&
        resource[0] !== '/') {
 
        var url = Url.parse(resource, false);
        resource = url.path;                        // Includes query
    }
 
    var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' +
                     options.ts + '\n' +
                     options.nonce + '\n' +
                     (options.method || '').toUpperCase() + '\n' +
                     resource + '\n' +
                     options.host.toLowerCase() + '\n' +
                     options.port + '\n' +
                     (options.hash || '') + '\n';
 
    if (options.ext) {
        normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n');
    }
 
    normalized += '\n';
 
    if (options.app) {
        normalized += options.app + '\n' +
                      (options.dlg || '') + '\n';
    }
 
    return normalized;
};
 
 
exports.calculatePayloadHash = function (payload, algorithm, contentType) {
 
    var hash = exports.initializePayloadHash(algorithm, contentType);
    hash.update(payload || '');
    return exports.finalizePayloadHash(hash);
};
 
 
exports.initializePayloadHash = function (algorithm, contentType) {
 
    var hash = Crypto.createHash(algorithm);
    hash.update('hawk.' + exports.headerVersion + '.payload\n');
    hash.update(Utils.parseContentType(contentType) + '\n');
    return hash;
};
 
 
exports.finalizePayloadHash = function (hash) {
 
    hash.update('\n');
    return hash.digest('base64');
};
 
 
exports.calculateTsMac = function (ts, credentials) {
 
    var hmac = Crypto.createHmac(credentials.algorithm, credentials.key);
    hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n');
    return hmac.digest('base64');
};
 
 
exports.timestampMessage = function (credentials, localtimeOffsetMsec) {
 
    var now = Utils.nowSecs(localtimeOffsetMsec);
    var tsm = exports.calculateTsMac(now, credentials);
    return { ts: now, tsm: tsm };
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/index.js

Statements: 100% (7 / 7)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (7 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17    1 1   1 1 1 1   1            
// Export sub-modules
 
exports.error = exports.Error = require('boom');
exports.sntp = require('sntp');
 
exports.server = require('./server');
exports.client = require('./client');
exports.crypto = require('./crypto');
exports.utils = require('./utils');
 
exports.uri = {
    authenticate: exports.server.authenticateBewit,
    getBewit: exports.client.getBewit
};
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/server.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/server.js

Statements: 9.66% (14 / 145)      Branches: 0% (0 / 140)      Functions: 0% (0 / 12)      Lines: 9.66% (14 / 145)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550    1 1 1 1 1         1                                                                                                                                                 1                                                                                                                                                                                                                                                                   1                           1                                     1                                                                                                                                 1     1                                                                                                                                                                                                                                                                                 1                                                                                                                                                                                       1          
// Load modules
 
var Boom = require('boom');
var Hoek = require('hoek');
var Cryptiles = require('cryptiles');
var Crypto = require('./crypto');
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {};
 
 
// Hawk authentication
 
/*
   req:                 node's HTTP request object or an object as follows:
 
                        var request = {
                            method: 'GET',
                            url: '/resource/4?a=1&b=2',
                            host: 'example.com',
                            port: 8080,
                            authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="'
                        };
 
   credentialsFunc:     required function to lookup the set of Hawk credentials based on the provided credentials id.
                        The credentials include the MAC key, MAC algorithm, and other attributes (such as username)
                        needed by the application. This function is the equivalent of verifying the username and
                        password in Basic authentication.
 
                        var credentialsFunc = function (id, callback) {
 
                            // Lookup credentials in database
                            db.lookup(id, function (err, item) {
 
                                if (err || !item) {
                                    return callback(err);
                                }
 
                                var credentials = {
                                    // Required
                                    key: item.key,
                                    algorithm: item.algorithm,
                                    // Application specific
                                    user: item.user
                                };
 
                                return callback(null, credentials);
                            });
                        };
 
   options: {
 
        hostHeaderName:        optional header field name, used to override the default 'Host' header when used
                               behind a cache of a proxy. Apache2 changes the value of the 'Host' header while preserving
                               the original (which is what the module must verify) in the 'x-forwarded-host' header field.
                               Only used when passed a node Http.ServerRequest object.
 
        nonceFunc:             optional nonce validation function. The function signature is function(key, nonce, ts, callback)
                               where 'callback' must be called using the signature function(err).
 
        timestampSkewSec:      optional number of seconds of permitted clock skew for incoming timestamps. Defaults to 60 seconds.
                               Provides a +/- skew which means actual allowed window is double the number of seconds.
 
        localtimeOffsetMsec:   optional local clock time offset express in a number of milliseconds (positive or negative).
                               Defaults to 0.
 
        payload:               optional payload for validation. The client calculates the hash value and includes it via the 'hash'
                               header attribute. The server always ensures the value provided has been included in the request
                               MAC. When this option is provided, it validates the hash value itself. Validation is done by calculating
                               a hash value over the entire payload (assuming it has already be normalized to the same format and
                               encoding used by the client to calculate the hash on request). If the payload is not available at the time
                               of authentication, the authenticatePayload() method can be used by passing it the credentials and
                               attributes.hash returned in the authenticate callback.
 
        host:                  optional host name override. Only used when passed a node request object.
        port:                  optional port override. Only used when passed a node request object.
    }
 
    callback: function (err, credentials, artifacts) { }
 */
 
exports.authenticate = function (req, credentialsFunc, options, callback) {
 
    callback = Hoek.nextTick(callback);
 
    // Default options
 
    options.nonceFunc = options.nonceFunc || internals.nonceFunc;
    options.timestampSkewSec = options.timestampSkewSec || 60;                                                  // 60 seconds
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);                           // Measure now before any other processing
 
    // Convert node Http request object to a request configuration object
 
    var request = Utils.parseRequest(req, options);
    if (request instanceof Error) {
        return callback(Boom.badRequest(request.message));
    }
 
    // Parse HTTP Authorization header
 
    var attributes = Utils.parseAuthorizationHeader(request.authorization);
    if (attributes instanceof Error) {
        return callback(attributes);
    }
 
    // Construct artifacts container
 
    var artifacts = {
        method: request.method,
        host: request.host,
        port: request.port,
        resource: request.url,
        ts: attributes.ts,
        nonce: attributes.nonce,
        hash: attributes.hash,
        ext: attributes.ext,
        app: attributes.app,
        dlg: attributes.dlg,
        mac: attributes.mac,
        id: attributes.id
    };
 
    // Verify required header attributes
 
    if (!attributes.id ||
        !attributes.ts ||
        !attributes.nonce ||
        !attributes.mac) {
 
        return callback(Boom.badRequest('Missing attributes'), null, artifacts);
    }
 
    // Fetch Hawk credentials
 
    credentialsFunc(attributes.id, function (err, credentials) {
 
        if (err) {
            return callback(err, credentials || null, artifacts);
        }
 
        if (!credentials) {
            return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, artifacts);
        }
 
        if (!credentials.key ||
            !credentials.algorithm) {
 
            return callback(Boom.internal('Invalid credentials'), credentials, artifacts);
        }
 
        if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
            return callback(Boom.internal('Unknown algorithm'), credentials, artifacts);
        }
 
        // Calculate MAC
 
        var mac = Crypto.calculateMac('header', credentials, artifacts);
        if (!Cryptiles.fixedTimeComparison(mac, attributes.mac)) {
            return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, artifacts);
        }
 
        // Check payload hash
 
        if (options.payload ||
            options.payload === '') {
 
            if (!attributes.hash) {
                return callback(Boom.unauthorized('Missing required payload hash', 'Hawk'), credentials, artifacts);
            }
 
            var hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, request.contentType);
            if (!Cryptiles.fixedTimeComparison(hash, attributes.hash)) {
                return callback(Boom.unauthorized('Bad payload hash', 'Hawk'), credentials, artifacts);
            }
        }
 
        // Check nonce
 
        options.nonceFunc(credentials.key, attributes.nonce, attributes.ts, function (err) {
 
            if (err) {
                return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials, artifacts);
            }
 
            // Check timestamp staleness
 
            if (Math.abs((attributes.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
                var tsm = Crypto.timestampMessage(credentials, options.localtimeOffsetMsec);
                return callback(Boom.unauthorized('Stale timestamp', 'Hawk', tsm), credentials, artifacts);
            }
 
            // Successful authentication
 
            return callback(null, credentials, artifacts);
        });
    });
};
 
 
// Authenticate payload hash - used when payload cannot be provided during authenticate()
 
/*
    payload:        raw request payload
    credentials:    from authenticate callback
    artifacts:      from authenticate callback
    contentType:    req.headers['content-type']
*/
 
exports.authenticatePayload = function (payload, credentials, artifacts, contentType) {
 
    var calculatedHash = Crypto.calculatePayloadHash(payload, credentials.algorithm, contentType);
    return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
};
 
 
// Authenticate payload hash - used when payload cannot be provided during authenticate()
 
/*
    calculatedHash: the payload hash calculated using Crypto.calculatePayloadHash()
    artifacts:      from authenticate callback
*/
 
exports.authenticatePayloadHash = function (calculatedHash, artifacts) {
 
    return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
};
 
 
// Generate a Server-Authorization header for a given response
 
/*
    credentials: {},                                        // Object received from authenticate()
    artifacts: {}                                           // Object received from authenticate(); 'mac', 'hash', and 'ext' - ignored
    options: {
        ext: 'application-specific',                        // Application specific data sent via the ext attribute
        payload: '{"some":"payload"}',                      // UTF-8 encoded string for body hash generation (ignored if hash provided)
        contentType: 'application/json',                    // Payload content-type (ignored if hash provided)
        hash: 'U4MKKSmiVxk37JCCrAVIjV='                     // Pre-calculated payload hash
    }
*/
 
exports.header = function (credentials, artifacts, options) {
 
    // Prepare inputs
 
    options = options || {};
 
    if (!artifacts ||
        typeof artifacts !== 'object' ||
        typeof options !== 'object') {
 
        return '';
    }
 
    artifacts = Hoek.clone(artifacts);
    delete artifacts.mac;
    artifacts.hash = options.hash;
    artifacts.ext = options.ext;
 
    // Validate credentials
 
    if (!credentials ||
        !credentials.key ||
        !credentials.algorithm) {
 
        // Invalid credential object
        return '';
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        return '';
    }
 
    // Calculate payload hash
 
    if (!artifacts.hash &&
        (options.payload || options.payload === '')) {
 
        artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
    }
 
    var mac = Crypto.calculateMac('response', credentials, artifacts);
 
    // Construct header
 
    var header = 'Hawk mac="' + mac + '"' +
                 (artifacts.hash ? ', hash="' + artifacts.hash + '"' : '');
 
    if (artifacts.ext !== null &&
        artifacts.ext !== undefined &&
        artifacts.ext !== '') {                       // Other falsey values allowed
 
        header += ', ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) + '"';
    }
 
    return header;
};
 
 
/*
 * Arguments and options are the same as authenticate() with the exception that the only supported options are:
 * 'hostHeaderName', 'localtimeOffsetMsec', 'host', 'port'
 */
 
 
//                       1     2             3           4
internals.bewitRegex = /^(\/.*)([\?&])bewit\=([^&$]*)(?:&(.+))?$/;
 
 
exports.authenticateBewit = function (req, credentialsFunc, options, callback) {
 
    callback = Hoek.nextTick(callback);
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);
 
    // Convert node Http request object to a request configuration object
 
    var request = Utils.parseRequest(req, options);
    if (request instanceof Error) {
        return callback(Boom.badRequest(request.message));
    }
 
    // Extract bewit
 
    if (request.url.length > Utils.limits.maxMatchLength) {
        return callback(Boom.badRequest('Resource path exceeds max length'));
    }
 
    var resource = request.url.match(internals.bewitRegex);
    if (!resource) {
        return callback(Boom.unauthorized(null, 'Hawk'));
    }
 
    // Bewit not empty
 
    if (!resource[3]) {
        return callback(Boom.unauthorized('Empty bewit', 'Hawk'));
    }
 
    // Verify method is GET
 
    if (request.method !== 'GET' &&
        request.method !== 'HEAD') {
 
        return callback(Boom.unauthorized('Invalid method', 'Hawk'));
    }
 
    // No other authentication
 
    if (request.authorization) {
        return callback(Boom.badRequest('Multiple authentications'));
    }
 
    // Parse bewit
 
    var bewitString = Hoek.base64urlDecode(resource[3]);
    if (bewitString instanceof Error) {
        return callback(Boom.badRequest('Invalid bewit encoding'));
    }
 
    // Bewit format: id\exp\mac\ext ('\' is used because it is a reserved header attribute character)
 
    var bewitParts = bewitString.split('\\');
    if (bewitParts.length !== 4) {
        return callback(Boom.badRequest('Invalid bewit structure'));
    }
 
    var bewit = {
        id: bewitParts[0],
        exp: parseInt(bewitParts[1], 10),
        mac: bewitParts[2],
        ext: bewitParts[3] || ''
    };
 
    if (!bewit.id ||
        !bewit.exp ||
        !bewit.mac) {
 
        return callback(Boom.badRequest('Missing bewit attributes'));
    }
 
    // Construct URL without bewit
 
    var url = resource[1];
    if (resource[4]) {
        url += resource[2] + resource[4];
    }
 
    // Check expiration
 
    if (bewit.exp * 1000 <= now) {
        return callback(Boom.unauthorized('Access expired', 'Hawk'), null, bewit);
    }
 
    // Fetch Hawk credentials
 
    credentialsFunc(bewit.id, function (err, credentials) {
 
        if (err) {
            return callback(err, credentials || null, bewit.ext);
        }
 
        if (!credentials) {
            return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, bewit);
        }
 
        if (!credentials.key ||
            !credentials.algorithm) {
 
            return callback(Boom.internal('Invalid credentials'), credentials, bewit);
        }
 
        if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
            return callback(Boom.internal('Unknown algorithm'), credentials, bewit);
        }
 
        // Calculate MAC
 
        var mac = Crypto.calculateMac('bewit', credentials, {
            ts: bewit.exp,
            nonce: '',
            method: 'GET',
            resource: url,
            host: request.host,
            port: request.port,
            ext: bewit.ext
        });
 
        if (!Cryptiles.fixedTimeComparison(mac, bewit.mac)) {
            return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, bewit);
        }
 
        // Successful authentication
 
        return callback(null, credentials, bewit);
    });
};
 
 
/*
 *  options are the same as authenticate() with the exception that the only supported options are:
 * 'nonceFunc', 'timestampSkewSec', 'localtimeOffsetMsec'
 */
 
exports.authenticateMessage = function (host, port, message, authorization, credentialsFunc, options, callback) {
 
    callback = Hoek.nextTick(callback);
 
    // Default options
 
    options.nonceFunc = options.nonceFunc || internals.nonceFunc;
    options.timestampSkewSec = options.timestampSkewSec || 60;                                                  // 60 seconds
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);                       // Measure now before any other processing
 
    // Validate authorization
 
    if (!authorization.id ||
        !authorization.ts ||
        !authorization.nonce ||
        !authorization.hash ||
        !authorization.mac) {
 
        return callback(Boom.badRequest('Invalid authorization'));
    }
 
    // Fetch Hawk credentials
 
    credentialsFunc(authorization.id, function (err, credentials) {
 
        if (err) {
            return callback(err, credentials || null);
        }
 
        if (!credentials) {
            return callback(Boom.unauthorized('Unknown credentials', 'Hawk'));
        }
 
        if (!credentials.key ||
            !credentials.algorithm) {
 
            return callback(Boom.internal('Invalid credentials'), credentials);
        }
 
        if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
            return callback(Boom.internal('Unknown algorithm'), credentials);
        }
 
        // Construct artifacts container
 
        var artifacts = {
            ts: authorization.ts,
            nonce: authorization.nonce,
            host: host,
            port: port,
            hash: authorization.hash
        };
 
        // Calculate MAC
 
        var mac = Crypto.calculateMac('message', credentials, artifacts);
        if (!Cryptiles.fixedTimeComparison(mac, authorization.mac)) {
            return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials);
        }
 
        // Check payload hash
 
        var hash = Crypto.calculatePayloadHash(message, credentials.algorithm);
        if (!Cryptiles.fixedTimeComparison(hash, authorization.hash)) {
            return callback(Boom.unauthorized('Bad message hash', 'Hawk'), credentials);
        }
 
        // Check nonce
 
        options.nonceFunc(credentials.key, authorization.nonce, authorization.ts, function (err) {
 
            if (err) {
                return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials);
            }
 
            // Check timestamp staleness
 
            if (Math.abs((authorization.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
                return callback(Boom.unauthorized('Stale timestamp'), credentials);
            }
 
            // Successful authentication
 
            return callback(null, credentials);
        });
    });
};
 
 
internals.nonceFunc = function (key, nonce, ts, nonceCallback) {
 
    return nonceCallback();         // No validation
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/utils.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/lib/utils.js

Statements: 20.83% (15 / 72)      Branches: 0% (0 / 54)      Functions: 0% (0 / 9)      Lines: 20.83% (15 / 72)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186    1 1         1     1           1               1     1                                                   1                       1                                                             1           1           1 1         1                                                                                                                               1            
// Load modules
 
var Sntp = require('sntp');
var Boom = require('boom');
 
 
// Declare internals
 
var internals = {};
 
 
exports.version = function () {
 
    return require('../package.json').version;
};
 
 
exports.limits = {
    maxMatchLength: 4096            // Limit the length of uris and headers to avoid a DoS attack on string matching
};
 
 
// Extract host and port from request
 
//                                            $1                            $2
internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/;              // (IPv4, hostname)|(IPv6)
 
 
exports.parseHost = function (req, hostHeaderName) {
 
    hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host');
    var hostHeader = req.headers[hostHeaderName];
    if (!hostHeader) {
        return null;
    }
 
    if (hostHeader.length > exports.limits.maxMatchLength) {
        return null;
    }
 
    var hostParts = hostHeader.match(internals.hostHeaderRegex);
    if (!hostParts) {
        return null;
    }
 
    return {
        name: hostParts[1],
        port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80))
    };
};
 
 
// Parse Content-Type header content
 
exports.parseContentType = function (header) {
 
    if (!header) {
        return '';
    }
 
    return header.split(';')[0].trim().toLowerCase();
};
 
 
// Convert node's  to request configuration object
 
exports.parseRequest = function (req, options) {
 
    if (!req.headers) {
        return req;
    }
 
    // Obtain host and port information
 
    var host;
    if (!options.host ||
        !options.port) {
 
        host = exports.parseHost(req, options.hostHeaderName);
        if (!host) {
            return new Error('Invalid Host header');
        }
    }
 
    var request = {
        method: req.method,
        url: req.url,
        host: options.host || host.name,
        port: options.port || host.port,
        authorization: req.headers.authorization,
        contentType: req.headers['content-type'] || ''
    };
 
    return request;
};
 
 
exports.now = function (localtimeOffsetMsec) {
 
    return Sntp.now() + (localtimeOffsetMsec || 0);
};
 
 
exports.nowSecs = function (localtimeOffsetMsec) {
 
    return Math.floor(exports.now(localtimeOffsetMsec) / 1000);
};
 
 
internals.authHeaderRegex = /^(\w+)(?:\s+(.*))?$/;                                      // Header: scheme[ something]
internals.attributeRegex = /^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/;   // !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9
 
 
// Parse Hawk HTTP Authorization header
 
exports.parseAuthorizationHeader = function (header, keys) {
 
    keys = keys || ['id', 'ts', 'nonce', 'hash', 'ext', 'mac', 'app', 'dlg'];
 
    if (!header) {
        return Boom.unauthorized(null, 'Hawk');
    }
 
    if (header.length > exports.limits.maxMatchLength) {
        return Boom.badRequest('Header length too long');
    }
 
    var headerParts = header.match(internals.authHeaderRegex);
    if (!headerParts) {
        return Boom.badRequest('Invalid header syntax');
    }
 
    var scheme = headerParts[1];
    if (scheme.toLowerCase() !== 'hawk') {
        return Boom.unauthorized(null, 'Hawk');
    }
 
    var attributesString = headerParts[2];
    if (!attributesString) {
        return Boom.badRequest('Invalid header syntax');
    }
 
    var attributes = {};
    var errorMessage = '';
    var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) {
 
        // Check valid attribute names
 
        if (keys.indexOf($1) === -1) {
            errorMessage = 'Unknown attribute: ' + $1;
            return;
        }
 
        // Allowed attribute value characters
 
        if ($2.match(internals.attributeRegex) === null) {
            errorMessage = 'Bad attribute value: ' + $1;
            return;
        }
 
        // Check for duplicates
 
        if (attributes.hasOwnProperty($1)) {
            errorMessage = 'Duplicate attribute: ' + $1;
            return;
        }
 
        attributes[$1] = $2;
        return '';
    });
 
    if (verify !== '') {
        return Boom.badRequest(errorMessage || 'Bad header format');
    }
 
    return attributes;
};
 
 
exports.unauthorized = function (message, attributes) {
 
    return Boom.unauthorized(message, 'Hawk', attributes);
};
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/boom/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/boom/lib/

Statements: 26.92% (35 / 130)      Branches: 0% (0 / 52)      Functions: 0% (0 / 32)      Lines: 26.92% (35 / 130)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/boom/lib/
File Statements Branches Functions Lines
index.js 26.92% (35 / 130) 0% (0 / 52) 0% (0 / 32) 26.92% (35 / 130)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/boom/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/boom/lib/index.js

Statements: 26.92% (35 / 130)      Branches: 0% (0 / 52)      Functions: 0% (0 / 32)      Lines: 26.92% (35 / 130)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320    1 1         1   1             1         1                 1                                                                     1                               1           1                                                                                                                                               1           1           1           1           1           1           1           1           1           1           1           1           1           1           1         1           1           1               1         1                           1           1           1           1           1              
// Load modules
 
var Http = require('http');
var Hoek = require('hoek');
 
 
// Declare internals
 
var internals = {};
 
exports.wrap = function (error, statusCode, message) {
 
    Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object');
    return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message));
};
 
 
exports.create = function (statusCode, message, data) {
 
    return internals.create(statusCode, message, data, exports.create);
};
 
internals.create = function (statusCode, message, data, ctor) {
 
    var error = new Error(message ? message : undefined);       // Avoids settings null message
    Error.captureStackTrace(error, ctor);                       // Filter the stack to our external API
    error.data = data || null;
    internals.initialize(error, statusCode);
    return error;
};
 
internals.initialize = function (error, statusCode, message) {
 
    var numberCode = parseInt(statusCode, 10);
    Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode);
 
    error.isBoom = true;
    error.isServer = numberCode >= 500;
 
    if (!error.hasOwnProperty('data')) {
        error.data = null;
    }
 
    error.output = {
        statusCode: numberCode,
        payload: {},
        headers: {}
    };
 
    error.reformat = internals.reformat;
    error.reformat();
 
    if (!message &&
        !error.message) {
 
        message = error.output.payload.error;
    }
 
    if (message) {
        error.message = (message + (error.message ? ': ' + error.message : ''));
    }
 
    return error;
};
 
 
internals.reformat = function () {
 
    this.output.payload.statusCode = this.output.statusCode;
    this.output.payload.error = Http.STATUS_CODES[this.output.statusCode] || 'Unknown';
 
    if (this.output.statusCode === 500) {
        this.output.payload.message = 'An internal server error occurred';              // Hide actual error from user
    }
    else if (this.message) {
        this.output.payload.message = this.message;
    }
};
 
 
// 4xx Client Errors
 
exports.badRequest = function (message, data) {
 
    return internals.create(400, message, data, exports.badRequest);
};
 
 
exports.unauthorized = function (message, scheme, attributes) {          // Or function (message, wwwAuthenticate[])
 
    var err = internals.create(401, message, undefined, exports.unauthorized);
 
    if (!scheme) {
        return err;
    }
 
    var wwwAuthenticate = '';
    var i = 0;
    var il = 0;
 
    if (typeof scheme === 'string') {
 
        // function (message, scheme, attributes)
 
        wwwAuthenticate = scheme;
 
        if (attributes || message) {
            err.output.payload.attributes = {};
        }
 
        if (attributes) {
            var names = Object.keys(attributes);
            for (i = 0, il = names.length; i < il; ++i) {
                var name = names[i];
                if (i) {
                    wwwAuthenticate += ',';
                }
 
                var value = attributes[name];
                if (value === null ||
                    value === undefined) {              // Value can be zero
 
                    value = '';
                }
                wwwAuthenticate += ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"';
                err.output.payload.attributes[name] = value;
            }
        }
 
        if (message) {
            if (attributes) {
                wwwAuthenticate += ',';
            }
            wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"';
            err.output.payload.attributes.error = message;
        }
        else {
            err.isMissing = true;
        }
    }
    else {
 
        // function (message, wwwAuthenticate[])
 
        var wwwArray = scheme;
        for (i = 0, il = wwwArray.length; i < il; ++i) {
            if (i) {
                wwwAuthenticate += ', ';
            }
 
            wwwAuthenticate += wwwArray[i];
        }
    }
 
    err.output.headers['WWW-Authenticate'] = wwwAuthenticate;
 
    return err;
};
 
 
exports.forbidden = function (message, data) {
 
    return internals.create(403, message, data, exports.forbidden);
};
 
 
exports.notFound = function (message, data) {
 
    return internals.create(404, message, data, exports.notFound);
};
 
 
exports.methodNotAllowed = function (message, data) {
 
    return internals.create(405, message, data, exports.methodNotAllowed);
};
 
 
exports.notAcceptable = function (message, data) {
 
    return internals.create(406, message, data, exports.notAcceptable);
};
 
 
exports.proxyAuthRequired = function (message, data) {
 
    return internals.create(407, message, data, exports.proxyAuthRequired);
};
 
 
exports.clientTimeout = function (message, data) {
 
    return internals.create(408, message, data, exports.clientTimeout);
};
 
 
exports.conflict = function (message, data) {
 
    return internals.create(409, message, data, exports.conflict);
};
 
 
exports.resourceGone = function (message, data) {
 
    return internals.create(410, message, data, exports.resourceGone);
};
 
 
exports.lengthRequired = function (message, data) {
 
    return internals.create(411, message, data, exports.lengthRequired);
};
 
 
exports.preconditionFailed = function (message, data) {
 
    return internals.create(412, message, data, exports.preconditionFailed);
};
 
 
exports.entityTooLarge = function (message, data) {
 
    return internals.create(413, message, data, exports.entityTooLarge);
};
 
 
exports.uriTooLong = function (message, data) {
 
    return internals.create(414, message, data, exports.uriTooLong);
};
 
 
exports.unsupportedMediaType = function (message, data) {
 
    return internals.create(415, message, data, exports.unsupportedMediaType);
};
 
 
exports.rangeNotSatisfiable = function (message, data) {
 
    return internals.create(416, message, data, exports.rangeNotSatisfiable);
};
 
 
exports.expectationFailed = function (message, data) {
 
    return internals.create(417, message, data, exports.expectationFailed);
};
 
exports.badData = function (message, data) {
 
    return internals.create(422, message, data, exports.badData);
};
 
 
exports.preconditionRequired = function (message, data) {
 
    return internals.create(428, message, data, exports.preconditionRequired);
};
 
 
exports.tooManyRequests = function (message, data) {
 
    return internals.create(429, message, data, exports.tooManyRequests);
};
 
 
// 5xx Server Errors
 
exports.internal = function (message, data, statusCode) {
 
    return internals.serverError(message, data, statusCode, exports.internal);
};
 
internals.serverError = function (message, data, statusCode, ctor) {
 
    var error;
    if (data instanceof Error) {
        error = exports.wrap(data, statusCode, message);
    } else {
        error = internals.create(statusCode || 500, message, undefined, ctor);
        error.data = data;
    }
 
    return error;
};
 
 
exports.notImplemented = function (message, data) {
 
    return internals.serverError(message, data, 501, exports.notImplemented);
};
 
 
exports.badGateway = function (message, data) {
 
    return internals.serverError(message, data, 502, exports.badGateway);
};
 
 
exports.serverTimeout = function (message, data) {
 
    return internals.serverError(message, data, 503, exports.serverTimeout);
};
 
 
exports.gatewayTimeout = function (message, data) {
 
    return internals.serverError(message, data, 504, exports.gatewayTimeout);
};
 
 
exports.badImplementation = function (message, data) {
 
    var err = internals.serverError(message, data, 500, exports.badImplementation);
    err.isDeveloperError = true;
    return err;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/

Statements: 22.22% (6 / 27)      Branches: 0% (0 / 14)      Functions: 0% (0 / 3)      Lines: 22.22% (6 / 27)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/
File Statements Branches Functions Lines
index.js 22.22% (6 / 27) 0% (0 / 14) 0% (0 / 3) 22.22% (6 / 27)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/index.js

Statements: 22.22% (6 / 27)      Branches: 0% (0 / 14)      Functions: 0% (0 / 3)      Lines: 22.22% (6 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70    1 1         1         1                       1                                       1                                                
// Load modules
 
var Crypto = require('crypto');
var Boom = require('boom');
 
 
// Declare internals
 
var internals = {};
 
 
// Generate a cryptographically strong pseudo-random data
 
exports.randomString = function (size) {
 
    var buffer = exports.randomBits((size + 1) * 6);
    if (buffer instanceof Error) {
        return buffer;
    }
 
    var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
    return string.slice(0, size);
};
 
 
exports.randomBits = function (bits) {
 
    if (!bits ||
        bits < 0) {
 
        return Boom.internal('Invalid random bits count');
    }
 
    var bytes = Math.ceil(bits / 8);
    try {
        return Crypto.randomBytes(bytes);
    }
    catch (err) {
        return Boom.internal('Failed generating random bits: ' + err.message);
    }
};
 
 
// Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match)
 
exports.fixedTimeComparison = function (a, b) {
 
    if (typeof a !== 'string' ||
        typeof b !== 'string') {
 
        return false;
    }
 
    var mismatch = (a.length === b.length ? 0 : 1);
    if (mismatch) {
        b = a;
    }
 
    for (var i = 0, il = a.length; i < il; ++i) {
        var ac = a.charCodeAt(i);
        var bc = b.charCodeAt(i);
        mismatch |= (ac ^ bc);
    }
 
    return (mismatch === 0);
};
 
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/

Statements: 13.33% (66 / 495)      Branches: 3.72% (13 / 349)      Functions: 1.69% (1 / 59)      Lines: 13.33% (66 / 495)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/
File Statements Branches Functions Lines
escape.js 29.79% (14 / 47) 48.15% (13 / 27) 14.29% (1 / 7) 29.79% (14 / 47)
index.js 11.61% (52 / 448) 0% (0 / 322) 0% (0 / 52) 11.61% (52 / 448)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/escape.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/escape.js

Statements: 29.79% (14 / 47)      Branches: 48.15% (13 / 27)      Functions: 14.29% (1 / 7)      Lines: 29.79% (14 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134    1     1                                               1                                               1                     1                               1                   1           1                           1   1   1   91                   68       1      
// Declare internals
 
var internals = {};
 
 
exports.escapeJavaScript = function (input) {
 
    if (!input) {
        return '';
    }
 
    var escaped = '';
 
    for (var i = 0, il = input.length; i < il; ++i) {
 
        var charCode = input.charCodeAt(i);
 
        if (internals.isSafe(charCode)) {
            escaped += input[i];
        }
        else {
            escaped += internals.escapeJavaScriptChar(charCode);
        }
    }
 
    return escaped;
};
 
 
exports.escapeHtml = function (input) {
 
    if (!input) {
        return '';
    }
 
    var escaped = '';
 
    for (var i = 0, il = input.length; i < il; ++i) {
 
        var charCode = input.charCodeAt(i);
 
        if (internals.isSafe(charCode)) {
            escaped += input[i];
        }
        else {
            escaped += internals.escapeHtmlChar(charCode);
        }
    }
 
    return escaped;
};
 
 
internals.escapeJavaScriptChar = function (charCode) {
 
    if (charCode >= 256) {
        return '\\u' + internals.padLeft('' + charCode, 4);
    }
 
    var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
    return '\\x' + internals.padLeft(hexValue, 2);
};
 
 
internals.escapeHtmlChar = function (charCode) {
 
    var namedEscape = internals.namedHtml[charCode];
    if (typeof namedEscape !== 'undefined') {
        return namedEscape;
    }
 
    if (charCode >= 256) {
        return '&#' + charCode + ';';
    }
 
    var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
    return '&#x' + internals.padLeft(hexValue, 2) + ';';
};
 
 
internals.padLeft = function (str, len) {
 
    while (str.length < len) {
        str = '0' + str;
    }
 
    return str;
};
 
 
internals.isSafe = function (charCode) {
 
    return (typeof internals.safeCharCodes[charCode] !== 'undefined');
};
 
 
internals.namedHtml = {
    '38': '&amp;',
    '60': '&lt;',
    '62': '&gt;',
    '34': '&quot;',
    '160': '&nbsp;',
    '162': '&cent;',
    '163': '&pound;',
    '164': '&curren;',
    '169': '&copy;',
    '174': '&reg;'
};
 
 
internals.safeCharCodes = (function () {
 
    var safe = {};
 
    for (var i = 32; i < 123; ++i) {
 
        if ((i >= 97) ||                    // a-z
            (i >= 65 && i <= 90) ||         // A-Z
            (i >= 48 && i <= 57) ||         // 0-9
            i === 32 ||                     // space
            i === 46 ||                     // .
            i === 44 ||                     // ,
            i === 45 ||                     // -
            i === 58 ||                     // :
            i === 95) {                     // _
 
            safe[i] = null;
        }
    }
 
    return safe;
}());
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/hoek/lib/index.js

Statements: 11.61% (52 / 448)      Branches: 0% (0 / 322)      Functions: 0% (0 / 52)      Lines: 11.61% (52 / 448)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995    1 1 1 1         1         1                                                                                                                                               1                                                                                                                       1                                         1                             1                               1                     1                                 1                                                 1                                                                                                                                                                                                                                     1                                       1                                               1                                                   1                                                                                                                                                                                                                                                           1                                     1                                                                               1                   1                       1                         1                                                   1               1     1                             1                                                 1             1           1           1             1           1           1                 1                 1                 1                                       1                   1           1           1                         1                                         1                                               1               1     1     1     1                                                                               1                             1                     1                        
// Load modules
 
var Crypto = require('crypto');
var Path = require('path');
var Util = require('util');
var Escape = require('./escape');
 
 
// Declare internals
 
var internals = {};
 
 
// Clone object or array
 
exports.clone = function (obj, seen) {
 
    if (typeof obj !== 'object' ||
        obj === null) {
 
        return obj;
    }
 
    seen = seen || { orig: [], copy: [] };
 
    var lookup = seen.orig.indexOf(obj);
    if (lookup !== -1) {
        return seen.copy[lookup];
    }
 
    var newObj;
    var cloneDeep = false;
 
    if (!Array.isArray(obj)) {
        if (Buffer.isBuffer(obj)) {
            newObj = new Buffer(obj);
        }
        else if (obj instanceof Date) {
            newObj = new Date(obj.getTime());
        }
        else if (obj instanceof RegExp) {
            newObj = new RegExp(obj);
        }
        else {
            var proto = Object.getPrototypeOf(obj);
            if (proto &&
                proto.isImmutable) {
 
                newObj = obj;
            }
            else {
                newObj = Object.create(proto);
                cloneDeep = true;
            }
        }
    }
    else {
        newObj = [];
        cloneDeep = true;
    }
 
    seen.orig.push(obj);
    seen.copy.push(newObj);
 
    if (cloneDeep) {
        var keys = Object.getOwnPropertyNames(obj);
        for (var i = 0, il = keys.length; i < il; ++i) {
            var key = keys[i];
            var descriptor = Object.getOwnPropertyDescriptor(obj, key);
            if (descriptor &&
                (descriptor.get ||
                 descriptor.set)) {
 
                Object.defineProperty(newObj, key, descriptor);
            }
            else {
                newObj[key] = exports.clone(obj[key], seen);
            }
        }
    }
 
    return newObj;
};
 
 
// Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied
/*eslint-disable */
exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) {
/*eslint-enable */
    exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object');
    exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
 
    if (!source) {
        return target;
    }
 
    if (Array.isArray(source)) {
        exports.assert(Array.isArray(target), 'Cannot merge array onto an object');
        if (isMergeArrays === false) {                                                  // isMergeArrays defaults to true
            target.length = 0;                                                          // Must not change target assignment
        }
 
        for (var i = 0, il = source.length; i < il; ++i) {
            target.push(exports.clone(source[i]));
        }
 
        return target;
    }
 
    var keys = Object.keys(source);
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var value = source[key];
        if (value &&
            typeof value === 'object') {
 
            if (!target[key] ||
                typeof target[key] !== 'object' ||
                (Array.isArray(target[key]) ^ Array.isArray(value)) ||
                value instanceof Date ||
                Buffer.isBuffer(value) ||
                value instanceof RegExp) {
 
                target[key] = exports.clone(value);
            }
            else {
                exports.merge(target[key], value, isNullOverride, isMergeArrays);
            }
        }
        else {
            if (value !== null &&
                value !== undefined) {                              // Explicit to preserve empty strings
 
                target[key] = value;
            }
            else if (isNullOverride !== false) {                    // Defaults to true
                target[key] = value;
            }
        }
    }
 
    return target;
};
 
 
// Apply options to a copy of the defaults
 
exports.applyToDefaults = function (defaults, options, isNullOverride) {
 
    exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
    exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
 
    if (!options) {                                                 // If no options, return null
        return null;
    }
 
    var copy = exports.clone(defaults);
 
    if (options === true) {                                         // If options is set to true, use defaults
        return copy;
    }
 
    return exports.merge(copy, options, isNullOverride === true, false);
};
 
 
// Clone an object except for the listed keys which are shallow copied
 
exports.cloneWithShallow = function (source, keys) {
 
    if (!source ||
        typeof source !== 'object') {
 
        return source;
    }
 
    var storage = internals.store(source, keys);    // Move shallow copy items to storage
    var copy = exports.clone(source);               // Deep copy the rest
    internals.restore(copy, source, storage);       // Shallow copy the stored items and restore
    return copy;
};
 
 
internals.store = function (source, keys) {
 
    var storage = {};
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        var value = exports.reach(source, key);
        if (value !== undefined) {
            storage[key] = value;
            internals.reachSet(source, key, undefined);
        }
    }
 
    return storage;
};
 
 
internals.restore = function (copy, source, storage) {
 
    var keys = Object.keys(storage);
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        internals.reachSet(copy, key, storage[key]);
        internals.reachSet(source, key, storage[key]);
    }
};
 
 
internals.reachSet = function (obj, key, value) {
 
    var path = key.split('.');
    var ref = obj;
    for (var i = 0, il = path.length; i < il; ++i) {
        var segment = path[i];
        if (i + 1 === il) {
            ref[segment] = value;
        }
 
        ref = ref[segment];
    }
};
 
 
// Apply options to defaults except for the listed keys which are shallow copied from option without merging
 
exports.applyToDefaultsWithShallow = function (defaults, options, keys) {
 
    exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
    exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
    exports.assert(keys && Array.isArray(keys), 'Invalid keys');
 
    if (!options) {                                                 // If no options, return null
        return null;
    }
 
    var copy = exports.cloneWithShallow(defaults, keys);
 
    if (options === true) {                                         // If options is set to true, use defaults
        return copy;
    }
 
    var storage = internals.store(options, keys);   // Move shallow copy items to storage
    exports.merge(copy, options, false, false);     // Deep copy the rest
    internals.restore(copy, options, storage);      // Shallow copy the stored items and restore
    return copy;
};
 
 
// Deep object or array comparison
 
exports.deepEqual = function (obj, ref, options, seen) {
 
    options = options || { prototype: true };
 
    var type = typeof obj;
 
    if (type !== typeof ref) {
        return false;
    }
 
    if (type !== 'object' ||
        obj === null ||
        ref === null) {
 
        if (obj === ref) {                                                      // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql
            return obj !== 0 || 1 / obj === 1 / ref;        // -0 / +0
        }
 
        return obj !== obj && ref !== ref;                  // NaN
    }
 
    seen = seen || [];
    if (seen.indexOf(obj) !== -1) {
        return true;                            // If previous comparison failed, it would have stopped execution
    }
 
    seen.push(obj);
 
    if (Array.isArray(obj)) {
        if (!Array.isArray(ref)) {
            return false;
        }
 
        if (!options.part && obj.length !== ref.length) {
            return false;
        }
 
        for (var i = 0, il = obj.length; i < il; ++i) {
            if (options.part) {
                var found = false;
                for (var r = 0, rl = ref.length; r < rl; ++r) {
                    if (exports.deepEqual(obj[i], ref[r], options, seen)) {
                        found = true;
                        break;
                    }
                }
 
                return found;
            }
 
            if (!exports.deepEqual(obj[i], ref[i], options, seen)) {
                return false;
            }
        }
 
        return true;
    }
 
    if (Buffer.isBuffer(obj)) {
        if (!Buffer.isBuffer(ref)) {
            return false;
        }
 
        if (obj.length !== ref.length) {
            return false;
        }
 
        for (var j = 0, jl = obj.length; j < jl; ++j) {
            if (obj[j] !== ref[j]) {
                return false;
            }
        }
 
        return true;
    }
 
    if (obj instanceof Date) {
        return (ref instanceof Date && obj.getTime() === ref.getTime());
    }
 
    if (obj instanceof RegExp) {
        return (ref instanceof RegExp && obj.toString() === ref.toString());
    }
 
    if (options.prototype) {
        if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) {
            return false;
        }
    }
 
    var keys = Object.getOwnPropertyNames(obj);
 
    if (!options.part && keys.length !== Object.getOwnPropertyNames(ref).length) {
        return false;
    }
 
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var descriptor = Object.getOwnPropertyDescriptor(obj, key);
        if (descriptor.get) {
            if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), options, seen)) {
                return false;
            }
        }
        else if (!exports.deepEqual(obj[key], ref[key], options, seen)) {
            return false;
        }
    }
 
    return true;
};
 
 
// Remove duplicate items from array
 
exports.unique = function (array, key) {
 
    var index = {};
    var result = [];
 
    for (var i = 0, il = array.length; i < il; ++i) {
        var id = (key ? array[i][key] : array[i]);
        if (index[id] !== true) {
 
            result.push(array[i]);
            index[id] = true;
        }
    }
 
    return result;
};
 
 
// Convert array into object
 
exports.mapToObject = function (array, key) {
 
    if (!array) {
        return null;
    }
 
    var obj = {};
    for (var i = 0, il = array.length; i < il; ++i) {
        if (key) {
            if (array[i][key]) {
                obj[array[i][key]] = true;
            }
        }
        else {
            obj[array[i]] = true;
        }
    }
 
    return obj;
};
 
 
// Find the common unique items in two arrays
 
exports.intersect = function (array1, array2, justFirst) {
 
    if (!array1 || !array2) {
        return [];
    }
 
    var common = [];
    var hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1);
    var found = {};
    for (var i = 0, il = array2.length; i < il; ++i) {
        if (hash[array2[i]] && !found[array2[i]]) {
            if (justFirst) {
                return array2[i];
            }
 
            common.push(array2[i]);
            found[array2[i]] = true;
        }
    }
 
    return (justFirst ? null : common);
};
 
 
// Test if the reference contains the values
 
exports.contain = function (ref, values, options) {
 
    /*
        string -> string(s)
        array -> item(s)
        object -> key(s)
        object -> object (key:value)
    */
 
    var valuePairs = null;
    if (typeof ref === 'object' &&
        typeof values === 'object' &&
        !Array.isArray(ref) &&
        !Array.isArray(values)) {
 
        valuePairs = values;
        values = Object.keys(values);
    }
    else {
        values = [].concat(values);
    }
 
    options = options || {};            // deep, once, only, part
 
    exports.assert(arguments.length >= 2, 'Insufficient arguments');
    exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object');
    exports.assert(values.length, 'Values array cannot be empty');
 
    var compare, compareFlags;
    if (options.deep) {
        compare = exports.deepEqual;
 
        var hasOnly = options.hasOwnProperty('only'), hasPart = options.hasOwnProperty('part');
 
        compareFlags = {
            prototype: hasOnly ? options.only : hasPart ? !options.part : false,
            part: hasOnly ? !options.only : hasPart ? options.part : true
        };
    }
    else {
        compare = function (a, b) {
 
            return a === b;
        };
    }
 
    var misses = false;
    var matches = new Array(values.length);
    for (var i = 0, il = matches.length; i < il; ++i) {
        matches[i] = 0;
    }
 
    if (typeof ref === 'string') {
        var pattern = '(';
        for (i = 0, il = values.length; i < il; ++i) {
            var value = values[i];
            exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value');
            pattern += (i ? '|' : '') + exports.escapeRegex(value);
        }
 
        var regex = new RegExp(pattern + ')', 'g');
        var leftovers = ref.replace(regex, function ($0, $1) {
 
            var index = values.indexOf($1);
            ++matches[index];
            return '';          // Remove from string
        });
 
        misses = !!leftovers;
    }
    else if (Array.isArray(ref)) {
        for (i = 0, il = ref.length; i < il; ++i) {
            for (var j = 0, jl = values.length, matched = false; j < jl && matched === false; ++j) {
                matched = compare(values[j], ref[i], compareFlags) && j;
            }
 
            if (matched !== false) {
                ++matches[matched];
            }
            else {
                misses = true;
            }
        }
    }
    else {
        var keys = Object.keys(ref);
        for (i = 0, il = keys.length; i < il; ++i) {
            var key = keys[i];
            var pos = values.indexOf(key);
            if (pos !== -1) {
                if (valuePairs &&
                    !compare(valuePairs[key], ref[key], compareFlags)) {
 
                    return false;
                }
 
                ++matches[pos];
            }
            else {
                misses = true;
            }
        }
    }
 
    var result = false;
    for (i = 0, il = matches.length; i < il; ++i) {
        result = result || !!matches[i];
        if ((options.once && matches[i] > 1) ||
            (!options.part && !matches[i])) {
 
            return false;
        }
    }
 
    if (options.only &&
        misses) {
 
        return false;
    }
 
    return result;
};
 
 
// Flatten array
 
exports.flatten = function (array, target) {
 
    var result = target || [];
 
    for (var i = 0, il = array.length; i < il; ++i) {
        if (Array.isArray(array[i])) {
            exports.flatten(array[i], result);
        }
        else {
            result.push(array[i]);
        }
    }
 
    return result;
};
 
 
// Convert an object key chain string ('a.b.c') to reference (object[a][b][c])
 
exports.reach = function (obj, chain, options) {
 
    if (chain === false ||
        chain === null ||
        typeof chain === 'undefined') {
 
        return obj;
    }
 
    options = options || {};
    if (typeof options === 'string') {
        options = { separator: options };
    }
 
    var path = chain.split(options.separator || '.');
    var ref = obj;
    for (var i = 0, il = path.length; i < il; ++i) {
        var key = path[i];
        if (key[0] === '-' && Array.isArray(ref)) {
            key = key.slice(1, key.length);
            key = ref.length - key;
        }
 
        if (!ref ||
            !ref.hasOwnProperty(key) ||
            (typeof ref !== 'object' && options.functions === false)) {         // Only object and function can have properties
 
            exports.assert(!options.strict || i + 1 === il, 'Missing segment', key, 'in reach path ', chain);
            exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
            ref = options.default;
            break;
        }
 
        ref = ref[key];
    }
 
    return ref;
};
 
 
exports.reachTemplate = function (obj, template, options) {
 
    return template.replace(/{([^}]+)}/g, function ($0, chain) {
 
        var value = exports.reach(obj, chain, options);
        return (value === undefined || value === null ? '' : value);
    });
};
 
 
exports.formatStack = function (stack) {
 
    var trace = [];
    for (var i = 0, il = stack.length; i < il; ++i) {
        var item = stack[i];
        trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);
    }
 
    return trace;
};
 
 
exports.formatTrace = function (trace) {
 
    var display = [];
 
    for (var i = 0, il = trace.length; i < il; ++i) {
        var row = trace[i];
        display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');
    }
 
    return display;
};
 
 
exports.callStack = function (slice) {
 
    // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
 
    var v8 = Error.prepareStackTrace;
    Error.prepareStackTrace = function (err, stack) {
 
        return stack;
    };
 
    var capture = {};
    Error.captureStackTrace(capture, arguments.callee);     /*eslint no-caller:0 */
    var stack = capture.stack;
 
    Error.prepareStackTrace = v8;
 
    var trace = exports.formatStack(stack);
 
    if (slice) {
        return trace.slice(slice);
    }
 
    return trace;
};
 
 
exports.displayStack = function (slice) {
 
    var trace = exports.callStack(slice === undefined ? 1 : slice + 1);
 
    return exports.formatTrace(trace);
};
 
 
exports.abortThrow = false;
 
 
exports.abort = function (message, hideStack) {
 
    if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {
        throw new Error(message || 'Unknown error');
    }
 
    var stack = '';
    if (!hideStack) {
        stack = exports.displayStack(1).join('\n\t');
    }
    console.log('ABORT: ' + message + '\n\t' + stack);
    process.exit(1);
};
 
 
exports.assert = function (condition /*, msg1, msg2, msg3 */) {
 
    if (condition) {
        return;
    }
 
    if (arguments.length === 2 && arguments[1] instanceof Error) {
        throw arguments[1];
    }
 
    var msgs = [];
    for (var i = 1, il = arguments.length; i < il; ++i) {
        if (arguments[i] !== '') {
            msgs.push(arguments[i]);            // Avoids Array.slice arguments leak, allowing for V8 optimizations
        }
    }
 
    msgs = msgs.map(function (msg) {
 
        return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg);
    });
    throw new Error(msgs.join(' ') || 'Unknown error');
};
 
 
exports.Timer = function () {
 
    this.ts = 0;
    this.reset();
};
 
 
exports.Timer.prototype.reset = function () {
 
    this.ts = Date.now();
};
 
 
exports.Timer.prototype.elapsed = function () {
 
    return Date.now() - this.ts;
};
 
 
exports.Bench = function () {
 
    this.ts = 0;
    this.reset();
};
 
 
exports.Bench.prototype.reset = function () {
 
    this.ts = exports.Bench.now();
};
 
 
exports.Bench.prototype.elapsed = function () {
 
    return exports.Bench.now() - this.ts;
};
 
 
exports.Bench.now = function () {
 
    var ts = process.hrtime();
    return (ts[0] * 1e3) + (ts[1] / 1e6);
};
 
 
// Escape string for Regex construction
 
exports.escapeRegex = function (string) {
 
    // Escape ^$.*+-?=!:|\/()[]{},
    return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
};
 
 
// Base64url (RFC 4648) encode
 
exports.base64urlEncode = function (value, encoding) {
 
    var buf = (Buffer.isBuffer(value) ? value : new Buffer(value, encoding || 'binary'));
    return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
};
 
 
// Base64url (RFC 4648) decode
 
exports.base64urlDecode = function (value, encoding) {
 
    if (value &&
        !/^[\w\-]*$/.test(value)) {
 
        return new Error('Invalid character');
    }
 
    try {
        var buf = new Buffer(value, 'base64');
        return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary'));
    }
    catch (err) {
        return err;
    }
};
 
 
// Escape attribute value for use in HTTP header
 
exports.escapeHeaderAttribute = function (attribute) {
 
    // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "
 
    exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');
 
    return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');                             // Escape quotes and slash
};
 
 
exports.escapeHtml = function (string) {
 
    return Escape.escapeHtml(string);
};
 
 
exports.escapeJavaScript = function (string) {
 
    return Escape.escapeJavaScript(string);
};
 
 
exports.nextTick = function (callback) {
 
    return function () {
 
        var args = arguments;
        process.nextTick(function () {
 
            callback.apply(null, args);
        });
    };
};
 
 
exports.once = function (method) {
 
    if (method._hoekOnce) {
        return method;
    }
 
    var once = false;
    var wrapped = function () {
 
        if (!once) {
            once = true;
            method.apply(null, arguments);
        }
    };
 
    wrapped._hoekOnce = true;
 
    return wrapped;
};
 
 
exports.isAbsolutePath = function (path, platform) {
 
    if (!path) {
        return false;
    }
 
    if (Path.isAbsolute) {                      // node >= 0.11
        return Path.isAbsolute(path);
    }
 
    platform = platform || process.platform;
 
    // Unix
 
    if (platform !== 'win32') {
        return path[0] === '/';
    }
 
    // Windows
 
    return !!/^(?:[a-zA-Z]:[\\\/])|(?:[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/])/.test(path);        // C:\ or \\something\something
};
 
 
exports.isInteger = function (value) {
 
    return (typeof value === 'number' &&
            parseFloat(value) === parseInt(value, 10) &&
            !isNaN(value));
};
 
 
exports.ignore = function () { };
 
 
exports.inherits = Util.inherits;
 
 
exports.format = Util.format;
 
 
exports.transform = function (source, transform, options) {
 
    exports.assert(source === null || source === undefined || typeof source === 'object' || Array.isArray(source), 'Invalid source object: must be null, undefined, an object, or an array');
 
    if (Array.isArray(source)) {
        var results = [];
        for (var i = 0, il = source.length; i < il; ++i) {
            results.push(exports.transform(source[i], transform, options));
        }
        return results;
    }
 
    var result = {};
    var keys = Object.keys(transform);
 
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var path = key.split('.');
        var sourcePath = transform[key];
 
        exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings');
 
        var segment;
        var res = result;
 
        while (path.length > 1) {
            segment = path.shift();
            if (!res[segment]) {
                res[segment] = {};
            }
            res = res[segment];
        }
        segment = path.shift();
        res[segment] = exports.reach(source, sourcePath, options);
    }
 
    return result;
};
 
 
exports.uniqueFilename = function (path, extension) {
 
    if (extension) {
        extension = extension[0] !== '.' ? '.' + extension : extension;
    }
    else {
        extension = '';
    }
 
    path = Path.resolve(path);
    var name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension;
    return Path.join(path, name);
};
 
 
exports.stringify = function () {
 
    try {
        return JSON.stringify.apply(null, arguments);
    }
    catch (err) {
        return '[Cannot display object: ' + err.message + ']';
    }
};
 
 
exports.shallow = function (source) {
 
    var target = {};
    var keys = Object.keys(source);
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        target[key] = source[key];
    }
 
    return target;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
module.exports = require('./lib');
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/lib/

Statements: 9.09% (16 / 176)      Branches: 0% (0 / 83)      Functions: 0% (0 / 22)      Lines: 9.64% (16 / 166)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/lib/
File Statements Branches Functions Lines
index.js 9.09% (16 / 176) 0% (0 / 83) 0% (0 / 22) 9.64% (16 / 166)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/hawk/node_modules/sntp/lib/index.js

Statements: 9.09% (16 / 176)      Branches: 0% (0 / 83)      Functions: 0% (0 / 22)      Lines: 9.64% (16 / 166)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414    1 1 1         1     1                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                         1                                 1                                     1               1                                                                                     1         1                                                       1                     1           1                         1        
// Load modules
 
var Dgram = require('dgram');
var Dns = require('dns');
var Hoek = require('hoek');
 
 
// Declare internals
 
var internals = {};
 
 
exports.time = function (options, callback) {
 
    if (arguments.length !== 2) {
        callback = arguments[0];
        options = {};
    }
 
    var settings = Hoek.clone(options);
    settings.host = settings.host || 'pool.ntp.org';
    settings.port = settings.port || 123;
    settings.resolveReference = settings.resolveReference || false;
 
    // Declare variables used by callback
 
    var timeoutId = 0;
    var sent = 0;
 
    // Ensure callback is only called once
 
    var finish = function (err, result) {
 
        if (timeoutId) {
            clearTimeout(timeoutId);
            timeoutId = 0;
        }
 
        socket.removeAllListeners();
        socket.once('error', internals.ignore);
        socket.close();
        return callback(err, result);
    };
 
    finish = Hoek.once(finish);
 
    // Create UDP socket
 
    var socket = Dgram.createSocket('udp4');
 
    socket.once('error', function (err) {
 
        return finish(err);
    });
 
    // Listen to incoming messages
 
    socket.on('message', function (buffer, rinfo) {
 
        var received = Date.now();
 
        var message = new internals.NtpMessage(buffer);
        if (!message.isValid) {
            return finish(new Error('Invalid server response'), message);
        }
 
        if (message.originateTimestamp !== sent) {
            return finish(new Error('Wrong originate timestamp'), message);
        }
 
        // Timestamp Name          ID   When Generated
        // ------------------------------------------------------------
        // Originate Timestamp     T1   time request sent by client
        // Receive Timestamp       T2   time request received by server
        // Transmit Timestamp      T3   time reply sent by server
        // Destination Timestamp   T4   time reply received by client
        //
        // The roundtrip delay d and system clock offset t are defined as:
        //
        // d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2
 
        var T1 = message.originateTimestamp;
        var T2 = message.receiveTimestamp;
        var T3 = message.transmitTimestamp;
        var T4 = received;
 
        message.d = (T4 - T1) - (T3 - T2);
        message.t = ((T2 - T1) + (T3 - T4)) / 2;
        message.receivedLocally = received;
 
        if (!settings.resolveReference ||
            message.stratum !== 'secondary') {
 
            return finish(null, message);
        }
 
        // Resolve reference IP address
 
        Dns.reverse(message.referenceId, function (err, domains) {
 
            if (/* $lab:coverage:off$ */ !err /* $lab:coverage:on$ */) {
                message.referenceHost = domains[0];
            }
 
            return finish(null, message);
        });
    });
 
    // Set timeout
 
    if (settings.timeout) {
        timeoutId = setTimeout(function () {
 
            timeoutId = 0;
            return finish(new Error('Timeout'));
        }, settings.timeout);
    }
 
    // Construct NTP message
 
    var message = new Buffer(48);
    for (var i = 0; i < 48; i++) {                      // Zero message
        message[i] = 0;
    }
 
    message[0] = (0 << 6) + (4 << 3) + (3 << 0)         // Set version number to 4 and Mode to 3 (client)
    sent = Date.now();
    internals.fromMsecs(sent, message, 40);               // Set transmit timestamp (returns as originate)
 
    // Send NTP request
 
    socket.send(message, 0, message.length, settings.port, settings.host, function (err, bytes) {
 
        if (err ||
            bytes !== 48) {
 
            return finish(err || new Error('Could not send entire message'));
        }
    });
};
 
 
internals.NtpMessage = function (buffer) {
 
    this.isValid = false;
 
    // Validate
 
    if (buffer.length !== 48) {
        return;
    }
 
    // Leap indicator
 
    var li = (buffer[0] >> 6);
    switch (li) {
        case 0: this.leapIndicator = 'no-warning'; break;
        case 1: this.leapIndicator = 'last-minute-61'; break;
        case 2: this.leapIndicator = 'last-minute-59'; break;
        case 3: this.leapIndicator = 'alarm'; break;
    }
 
    // Version
 
    var vn = ((buffer[0] & 0x38) >> 3);
    this.version = vn;
 
    // Mode
 
    var mode = (buffer[0] & 0x7);
    switch (mode) {
        case 1: this.mode = 'symmetric-active'; break;
        case 2: this.mode = 'symmetric-passive'; break;
        case 3: this.mode = 'client'; break;
        case 4: this.mode = 'server'; break;
        case 5: this.mode = 'broadcast'; break;
        case 0:
        case 6:
        case 7: this.mode = 'reserved'; break;
    }
 
    // Stratum
 
    var stratum = buffer[1];
    if (stratum === 0) {
        this.stratum = 'death';
    }
    else if (stratum === 1) {
        this.stratum = 'primary';
    }
    else if (stratum <= 15) {
        this.stratum = 'secondary';
    }
    else {
        this.stratum = 'reserved';
    }
 
    // Poll interval (msec)
 
    this.pollInterval = Math.round(Math.pow(2, buffer[2])) * 1000;
 
    // Precision (msecs)
 
    this.precision = Math.pow(2, buffer[3]) * 1000;
 
    // Root delay (msecs)
 
    var rootDelay = 256 * (256 * (256 * buffer[4] + buffer[5]) + buffer[6]) + buffer[7];
    this.rootDelay = 1000 * (rootDelay / 0x10000);
 
    // Root dispersion (msecs)
 
    this.rootDispersion = ((buffer[8] << 8) + buffer[9] + ((buffer[10] << 8) + buffer[11]) / Math.pow(2, 16)) * 1000;
 
    // Reference identifier
 
    this.referenceId = '';
    switch (this.stratum) {
        case 'death':
        case 'primary':
            this.referenceId = String.fromCharCode(buffer[12]) + String.fromCharCode(buffer[13]) + String.fromCharCode(buffer[14]) + String.fromCharCode(buffer[15]);
            break;
        case 'secondary':
            this.referenceId = '' + buffer[12] + '.' + buffer[13] + '.' + buffer[14] + '.' + buffer[15];
            break;
    }
 
    // Reference timestamp
 
    this.referenceTimestamp = internals.toMsecs(buffer, 16);
 
    // Originate timestamp
 
    this.originateTimestamp = internals.toMsecs(buffer, 24);
 
    // Receive timestamp
 
    this.receiveTimestamp = internals.toMsecs(buffer, 32);
 
    // Transmit timestamp
 
    this.transmitTimestamp = internals.toMsecs(buffer, 40);
 
    // Validate
 
    if (this.version === 4 &&
        this.stratum !== 'reserved' &&
        this.mode === 'server' &&
        this.originateTimestamp &&
        this.receiveTimestamp &&
        this.transmitTimestamp) {
 
        this.isValid = true;
    }
 
    return this;
};
 
 
internals.toMsecs = function (buffer, offset) {
 
    var seconds = 0;
    var fraction = 0;
 
    for (var i = 0; i < 4; ++i) {
        seconds = (seconds * 256) + buffer[offset + i];
    }
 
    for (i = 4; i < 8; ++i) {
        fraction = (fraction * 256) + buffer[offset + i];
    }
 
    return ((seconds - 2208988800 + (fraction / Math.pow(2, 32))) * 1000);
};
 
 
internals.fromMsecs = function (ts, buffer, offset) {
 
    var seconds = Math.floor(ts / 1000) + 2208988800;
    var fraction = Math.round((ts % 1000) / 1000 * Math.pow(2, 32));
 
    buffer[offset + 0] = (seconds & 0xFF000000) >> 24;
    buffer[offset + 1] = (seconds & 0x00FF0000) >> 16;
    buffer[offset + 2] = (seconds & 0x0000FF00) >> 8;
    buffer[offset + 3] = (seconds & 0x000000FF);
 
    buffer[offset + 4] = (fraction & 0xFF000000) >> 24;
    buffer[offset + 5] = (fraction & 0x00FF0000) >> 16;
    buffer[offset + 6] = (fraction & 0x0000FF00) >> 8;
    buffer[offset + 7] = (fraction & 0x000000FF);
};
 
 
// Offset singleton
 
internals.last = {
    offset: 0,
    expires: 0,
    host: '',
    port: 0
};
 
 
exports.offset = function (options, callback) {
 
    if (arguments.length !== 2) {
        callback = arguments[0];
        options = {};
    }
 
    var now = Date.now();
    var clockSyncRefresh = options.clockSyncRefresh || 24 * 60 * 60 * 1000;                    // Daily
 
    if (internals.last.offset &&
        internals.last.host === options.host &&
        internals.last.port === options.port &&
        now < internals.last.expires) {
 
        process.nextTick(function () {
 
            callback(null, internals.last.offset);
        });
 
        return;
    }
 
    exports.time(options, function (err, time) {
 
        if (err) {
            return callback(err, 0);
        }
 
        internals.last = {
            offset: Math.round(time.t),
            expires: now + clockSyncRefresh,
            host: options.host,
            port: options.port
        };
 
        return callback(null, internals.last.offset);
    });
};
 
 
// Now singleton
 
internals.now = {
    intervalId: 0
};
 
 
exports.start = function (options, callback) {
 
    if (arguments.length !== 2) {
        callback = arguments[0];
        options = {};
    }
 
    if (internals.now.intervalId) {
        process.nextTick(function () {
 
            callback();
        });
 
        return;
    }
 
    exports.offset(options, function (err, offset) {
 
        internals.now.intervalId = setInterval(function () {
 
            exports.offset(options, function () { });
        }, options.clockSyncRefresh || 24 * 60 * 60 * 1000);                                // Daily
 
        return callback();
    });
};
 
 
exports.stop = function () {
 
    if (!internals.now.intervalId) {
        return;
    }
 
    clearInterval(internals.now.intervalId);
    internals.now.intervalId = 0;
};
 
 
exports.isLive = function () {
 
    return !!internals.now.intervalId;
};
 
 
exports.now = function () {
 
    var now = Date.now();
    if (!exports.isLive() ||
        now >= internals.last.expires) {
 
        return now;
    }
 
    return now + internals.last.offset;
};
 
 
internals.ignore = function () {
 
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/

Statements: 18.64% (71 / 381)      Branches: 0% (0 / 188)      Functions: 0% (0 / 30)      Lines: 18.68% (71 / 380)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/
File Statements Branches Functions Lines
index.js 100% (5 / 5) 100% (0 / 0) 100% (0 / 0) 100% (5 / 5)
parser.js 15.91% (21 / 132) 0% (0 / 78) 0% (0 / 9) 16.03% (21 / 131)
signer.js 14.04% (24 / 171) 0% (0 / 82) 0% (0 / 13) 14.04% (24 / 171)
utils.js 32.35% (11 / 34) 0% (0 / 12) 0% (0 / 6) 32.35% (11 / 34)
verify.js 25.64% (10 / 39) 0% (0 / 16) 0% (0 / 2) 25.64% (10 / 39)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/index.js

Statements: 100% (5 / 5)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (5 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31    1 1 1 1           1                                      
// Copyright 2015 Joyent, Inc.
 
var parser = require('./parser');
var signer = require('./signer');
var verify = require('./verify');
var utils = require('./utils');
 
 
 
///--- API
 
module.exports = {
 
  parse: parser.parseRequest,
  parseRequest: parser.parseRequest,
 
  sign: signer.signRequest,
  signRequest: signer.signRequest,
  createSigner: signer.createSigner,
  isSigner: signer.isSigner,
 
  sshKeyToPEM: utils.sshKeyToPEM,
  sshKeyFingerprint: utils.fingerprint,
  pemToRsaSSHKey: utils.pemToRsaSSHKey,
 
  verify: verify.verifySignature,
  verifySignature: verify.verifySignature,
  verifyHMAC: verify.verifyHMAC
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/parser.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/parser.js

Statements: 15.91% (21 / 132)      Branches: 0% (0 / 78)      Functions: 0% (0 / 9)      Lines: 16.03% (21 / 131)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320    1 1 1           1 1 1 1 1   1         1                     1     1     1     1     1     1     1     1   1     1       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
// Copyright 2012 Joyent, Inc.  All rights reserved.
 
var assert = require('assert-plus');
var util = require('util');
var utils = require('./utils');
 
 
 
///--- Globals
 
var HASH_ALGOS = utils.HASH_ALGOS;
var PK_ALGOS = utils.PK_ALGOS;
var HttpSignatureError = utils.HttpSignatureError;
var InvalidAlgorithmError = utils.InvalidAlgorithmError;
var validateAlgorithm = utils.validateAlgorithm;
 
var State = {
  New: 0,
  Params: 1
};
 
var ParamsState = {
  Name: 0,
  Quote: 1,
  Value: 2,
  Comma: 3
};
 
 
///--- Specific Errors
 
 
function ExpiredRequestError(message) {
  HttpSignatureError.call(this, message, ExpiredRequestError);
}
util.inherits(ExpiredRequestError, HttpSignatureError);
 
 
function InvalidHeaderError(message) {
  HttpSignatureError.call(this, message, InvalidHeaderError);
}
util.inherits(InvalidHeaderError, HttpSignatureError);
 
 
function InvalidParamsError(message) {
  HttpSignatureError.call(this, message, InvalidParamsError);
}
util.inherits(InvalidParamsError, HttpSignatureError);
 
 
function MissingHeaderError(message) {
  HttpSignatureError.call(this, message, MissingHeaderError);
}
util.inherits(MissingHeaderError, HttpSignatureError);
 
function StrictParsingError(message) {
  HttpSignatureError.call(this, message, StrictParsingError);
}
util.inherits(StrictParsingError, HttpSignatureError);
 
///--- Exported API
 
module.exports = {
 
  /**
   * Parses the 'Authorization' header out of an http.ServerRequest object.
   *
   * Note that this API will fully validate the Authorization header, and throw
   * on any error.  It will not however check the signature, or the keyId format
   * as those are specific to your environment.  You can use the options object
   * to pass in extra constraints.
   *
   * As a response object you can expect this:
   *
   *     {
   *       "scheme": "Signature",
   *       "params": {
   *         "keyId": "foo",
   *         "algorithm": "rsa-sha256",
   *         "headers": [
   *           "date" or "x-date",
   *           "digest"
   *         ],
   *         "signature": "base64"
   *       },
   *       "signingString": "ready to be passed to crypto.verify()"
   *     }
   *
   * @param {Object} request an http.ServerRequest.
   * @param {Object} options an optional options object with:
   *                   - clockSkew: allowed clock skew in seconds (default 300).
   *                   - headers: required header names (def: date or x-date)
   *                   - algorithms: algorithms to support (default: all).
   *                   - strict: should enforce latest spec parsing
   *                             (default: false).
   * @return {Object} parsed out object (see above).
   * @throws {TypeError} on invalid input.
   * @throws {InvalidHeaderError} on an invalid Authorization header error.
   * @throws {InvalidParamsError} if the params in the scheme are invalid.
   * @throws {MissingHeaderError} if the params indicate a header not present,
   *                              either in the request headers from the params,
   *                              or not in the params from a required header
   *                              in options.
   * @throws {StrictParsingError} if old attributes are used in strict parsing
   *                              mode.
   * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew.
   */
  parseRequest: function parseRequest(request, options) {
    assert.object(request, 'request');
    assert.object(request.headers, 'request.headers');
    if (options === undefined) {
      options = {};
    }
    if (options.headers === undefined) {
      options.headers = [request.headers['x-date'] ? 'x-date' : 'date'];
    }
    assert.object(options, 'options');
    assert.arrayOfString(options.headers, 'options.headers');
    assert.optionalNumber(options.clockSkew, 'options.clockSkew');
 
    if (!request.headers.authorization)
      throw new MissingHeaderError('no authorization header present in ' +
                                   'the request');
 
    options.clockSkew = options.clockSkew || 300;
 
 
    var i = 0;
    var state = State.New;
    var substate = ParamsState.Name;
    var tmpName = '';
    var tmpValue = '';
 
    var parsed = {
      scheme: '',
      params: {},
      signingString: '',
 
      get algorithm() {
        return this.params.algorithm.toUpperCase();
      },
 
      get keyId() {
        return this.params.keyId;
      }
    };
 
    var authz = request.headers.authorization;
    for (i = 0; i < authz.length; i++) {
      var c = authz.charAt(i);
 
      switch (Number(state)) {
 
      case State.New:
        if (c !== ' ') parsed.scheme += c;
        else state = State.Params;
        break;
 
      case State.Params:
        switch (Number(substate)) {
 
        case ParamsState.Name:
          var code = c.charCodeAt(0);
          // restricted name of A-Z / a-z
          if ((code >= 0x41 && code <= 0x5a) || // A-Z
              (code >= 0x61 && code <= 0x7a)) { // a-z
            tmpName += c;
          } else if (c === '=') {
            if (tmpName.length === 0)
              throw new InvalidHeaderError('bad param format');
            substate = ParamsState.Quote;
          } else {
            throw new InvalidHeaderError('bad param format');
          }
          break;
 
        case ParamsState.Quote:
          if (c === '"') {
            tmpValue = '';
            substate = ParamsState.Value;
          } else {
            throw new InvalidHeaderError('bad param format');
          }
          break;
 
        case ParamsState.Value:
          if (c === '"') {
            parsed.params[tmpName] = tmpValue;
            substate = ParamsState.Comma;
          } else {
            tmpValue += c;
          }
          break;
 
        case ParamsState.Comma:
          if (c === ',') {
            tmpName = '';
            substate = ParamsState.Name;
          } else {
            throw new InvalidHeaderError('bad param format');
          }
          break;
 
        default:
          throw new Error('Invalid substate');
        }
        break;
 
      default:
        throw new Error('Invalid substate');
      }
 
    }
 
    if (!parsed.params.headers || parsed.params.headers === '') {
      if (request.headers['x-date']) {
        parsed.params.headers = ['x-date'];
      } else {
        parsed.params.headers = ['date'];
      }
    } else {
      parsed.params.headers = parsed.params.headers.split(' ');
    }
 
    // Minimally validate the parsed object
    if (!parsed.scheme || parsed.scheme !== 'Signature')
      throw new InvalidHeaderError('scheme was not "Signature"');
 
    if (!parsed.params.keyId)
      throw new InvalidHeaderError('keyId was not specified');
 
    if (!parsed.params.algorithm)
      throw new InvalidHeaderError('algorithm was not specified');
 
    if (!parsed.params.signature)
      throw new InvalidHeaderError('signature was not specified');
 
    // Check the algorithm against the official list
    parsed.params.algorithm = parsed.params.algorithm.toLowerCase();
    try {
      validateAlgorithm(parsed.params.algorithm);
    } catch (e) {
      if (e instanceof InvalidAlgorithmError)
        throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' +
          'supported'));
      else
        throw (e);
    }
 
    // Build the signingString
    for (i = 0; i < parsed.params.headers.length; i++) {
      var h = parsed.params.headers[i].toLowerCase();
      parsed.params.headers[i] = h;
 
      if (h === 'request-line') {
        if (!options.strict) {
          /*
           * We allow headers from the older spec drafts if strict parsing isn't
           * specified in options.
           */
          parsed.signingString +=
            request.method + ' ' + request.url + ' HTTP/' + request.httpVersion;
        } else {
          /* Strict parsing doesn't allow older draft headers. */
          throw (new StrictParsingError('request-line is not a valid header ' +
            'with strict parsing enabled.'));
        }
      } else if (h === '(request-target)') {
        parsed.signingString +=
          '(request-target): ' + request.method.toLowerCase() + ' ' +
          request.url;
      } else {
        var value = request.headers[h];
        if (value === undefined)
          throw new MissingHeaderError(h + ' was not in the request');
        parsed.signingString += h + ': ' + value;
      }
 
      if ((i + 1) < parsed.params.headers.length)
        parsed.signingString += '\n';
    }
 
    // Check against the constraints
    var date;
    if (request.headers.date || request.headers['x-date']) {
        if (request.headers['x-date']) {
          date = new Date(request.headers['x-date']);
        } else {
          date = new Date(request.headers.date);
        }
      var now = new Date();
      var skew = Math.abs(now.getTime() - date.getTime());
 
      if (skew > options.clockSkew * 1000) {
        throw new ExpiredRequestError('clock skew of ' +
                                      (skew / 1000) +
                                      's was greater than ' +
                                      options.clockSkew + 's');
      }
    }
 
    options.headers.forEach(function (hdr) {
      // Remember that we already checked any headers in the params
      // were in the request, so if this passes we're good.
      if (parsed.params.headers.indexOf(hdr) < 0)
        throw new MissingHeaderError(hdr + ' was not a signed header');
    });
 
    if (options.algorithms) {
      if (options.algorithms.indexOf(parsed.params.algorithm) === -1)
        throw new InvalidParamsError(parsed.params.algorithm +
                                     ' is not a supported algorithm');
    }
 
    return parsed;
  }
 
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/signer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/signer.js

Statements: 14.04% (24 / 171)      Branches: 0% (0 / 82)      Functions: 0% (0 / 13)      Lines: 14.04% (24 / 171)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401    1 1 1 1 1 1 1   1   1 1 1 1 1       1         1     1   1     1     1                                                                                                                                                                         1                                                 1                   1                         1                                                                                                           1                                                                                                                                                                                                                                                                                                                                                                  
// Copyright 2012 Joyent, Inc.  All rights reserved.
 
var assert = require('assert-plus');
var crypto = require('crypto');
var http = require('http');
var util = require('util');
var sshpk = require('sshpk');
var jsprim = require('jsprim');
var utils = require('./utils');
 
var sprintf = require('util').format;
 
var HASH_ALGOS = utils.HASH_ALGOS;
var PK_ALGOS = utils.PK_ALGOS;
var InvalidAlgorithmError = utils.InvalidAlgorithmError;
var HttpSignatureError = utils.HttpSignatureError;
var validateAlgorithm = utils.validateAlgorithm;
 
///--- Globals
 
var AUTHZ_FMT =
  'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
 
///--- Specific Errors
 
function MissingHeaderError(message) {
  HttpSignatureError.call(this, message, MissingHeaderError);
}
util.inherits(MissingHeaderError, HttpSignatureError);
 
function StrictParsingError(message) {
  HttpSignatureError.call(this, message, StrictParsingError);
}
util.inherits(StrictParsingError, HttpSignatureError);
 
/* See createSigner() */
function RequestSigner(options) {
  assert.object(options, 'options');
 
  var alg = [];
  if (options.algorithm !== undefined) {
    assert.string(options.algorithm, 'options.algorithm');
    alg = validateAlgorithm(options.algorithm);
  }
  this.rs_alg = alg;
 
  /*
   * RequestSigners come in two varieties: ones with an rs_signFunc, and ones
   * with an rs_signer.
   *
   * rs_signFunc-based RequestSigners have to build up their entire signing
   * string within the rs_lines array and give it to rs_signFunc as a single
   * concat'd blob. rs_signer-based RequestSigners can add a line at a time to
   * their signing state by using rs_signer.update(), thus only needing to
   * buffer the hash function state and one line at a time.
   */
  if (options.sign !== undefined) {
    assert.func(options.sign, 'options.sign');
    this.rs_signFunc = options.sign;
 
  } else if (alg[0] === 'hmac' && options.key !== undefined) {
    assert.string(options.keyId, 'options.keyId');
    this.rs_keyId = options.keyId;
 
    if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
      throw (new TypeError('options.key for HMAC must be a string or Buffer'));
 
    /*
     * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their
     * data in chunks rather than requiring it all to be given in one go
     * at the end, so they are more similar to signers than signFuncs.
     */
    this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key);
    this.rs_signer.sign = function () {
      var digest = this.digest('base64');
      return ({
        hashAlgorithm: alg[1],
        toString: function () { return (digest); }
      });
    };
 
  } else if (options.key !== undefined) {
    var key = options.key;
    if (typeof (key) === 'string' || Buffer.isBuffer(key))
      key = sshpk.parsePrivateKey(key);
 
    assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
      'options.key must be a sshpk.PrivateKey');
    this.rs_key = key;
 
    assert.string(options.keyId, 'options.keyId');
    this.rs_keyId = options.keyId;
 
    if (!PK_ALGOS[key.type]) {
      throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
        'keys are not supported'));
    }
 
    if (alg[0] !== undefined && key.type !== alg[0]) {
      throw (new InvalidAlgorithmError('options.key must be a ' +
        alg[0].toUpperCase() + ' key, was given a ' +
        key.type.toUpperCase() + ' key instead'));
    }
 
    this.rs_signer = key.createSign(alg[1]);
 
  } else {
    throw (new TypeError('options.sign (func) or options.key is required'));
  }
 
  this.rs_headers = [];
  this.rs_lines = [];
}
 
/**
 * Adds a header to be signed, with its value, into this signer.
 *
 * @param {String} header
 * @param {String} value
 * @return {String} value written
 */
RequestSigner.prototype.writeHeader = function (header, value) {
  assert.string(header, 'header');
  header = header.toLowerCase();
  assert.string(value, 'value');
 
  this.rs_headers.push(header);
 
  if (this.rs_signFunc) {
    this.rs_lines.push(header + ': ' + value);
 
  } else {
    var line = header + ': ' + value;
    if (this.rs_headers.length > 0)
      line = '\n' + line;
    this.rs_signer.update(line);
  }
 
  return (value);
};
 
/**
 * Adds a default Date header, returning its value.
 *
 * @return {String}
 */
RequestSigner.prototype.writeDateHeader = function () {
  return (this.writeHeader('date', jsprim.rfc1123(new Date())));
};
 
/**
 * Adds the request target line to be signed.
 *
 * @param {String} method, HTTP method (e.g. 'get', 'post', 'put')
 * @param {String} path
 */
RequestSigner.prototype.writeTarget = function (method, path) {
  assert.string(method, 'method');
  assert.string(path, 'path');
  method = method.toLowerCase();
  this.writeHeader('(request-target)', method + ' ' + path);
};
 
/**
 * Calculate the value for the Authorization header on this request
 * asynchronously.
 *
 * @param {Func} callback (err, authz)
 */
RequestSigner.prototype.sign = function (cb) {
  assert.func(cb, 'callback');
 
  if (this.rs_headers.length < 1)
    throw (new Error('At least one header must be signed'));
 
  var alg, authz;
  if (this.rs_signFunc) {
    var data = this.rs_lines.join('\n');
    var self = this;
    this.rs_signFunc(data, function (err, sig) {
      if (err) {
        cb(err);
        return;
      }
      try {
        assert.object(sig, 'signature');
        assert.string(sig.keyId, 'signature.keyId');
        assert.string(sig.algorithm, 'signature.algorithm');
        assert.string(sig.signature, 'signature.signature');
        alg = validateAlgorithm(sig.algorithm);
 
        authz = sprintf(AUTHZ_FMT,
          sig.keyId,
          sig.algorithm,
          self.rs_headers.join(' '),
          sig.signature);
      } catch (e) {
        cb(e);
        return;
      }
      cb(null, authz);
    });
 
  } else {
    try {
      var sigObj = this.rs_signer.sign();
    } catch (e) {
      cb(e);
      return;
    }
    alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm;
    var signature = sigObj.toString();
    authz = sprintf(AUTHZ_FMT,
      this.rs_keyId,
      alg,
      this.rs_headers.join(' '),
      signature);
    cb(null, authz);
  }
};
 
///--- Exported API
 
module.exports = {
  /**
   * Identifies whether a given object is a request signer or not.
   *
   * @param {Object} object, the object to identify
   * @returns {Boolean}
   */
  isSigner: function (obj) {
    if (typeof (obj) === 'object' && obj instanceof RequestSigner)
      return (true);
    return (false);
  },
 
  /**
   * Creates a request signer, used to asynchronously build a signature
   * for a request (does not have to be an http.ClientRequest).
   *
   * @param {Object} options, either:
   *                   - {String} keyId
   *                   - {String|Buffer} key
   *                   - {String} algorithm (optional, required for HMAC)
   *                 or:
   *                   - {Func} sign (data, cb)
   * @return {RequestSigner}
   */
  createSigner: function createSigner(options) {
    return (new RequestSigner(options));
  },
 
  /**
   * Adds an 'Authorization' header to an http.ClientRequest object.
   *
   * Note that this API will add a Date header if it's not already set. Any
   * other headers in the options.headers array MUST be present, or this
   * will throw.
   *
   * You shouldn't need to check the return type; it's just there if you want
   * to be pedantic.
   *
   * The optional flag indicates whether parsing should use strict enforcement
   * of the version draft-cavage-http-signatures-04 of the spec or beyond.
   * The default is to be loose and support
   * older versions for compatibility.
   *
   * @param {Object} request an instance of http.ClientRequest.
   * @param {Object} options signing parameters object:
   *                   - {String} keyId required.
   *                   - {String} key required (either a PEM or HMAC key).
   *                   - {Array} headers optional; defaults to ['date'].
   *                   - {String} algorithm optional (unless key is HMAC);
   *                              default is the same as the sshpk default
   *                              signing algorithm for the type of key given
   *                   - {String} httpVersion optional; defaults to '1.1'.
   *                   - {Boolean} strict optional; defaults to 'false'.
   * @return {Boolean} true if Authorization (and optionally Date) were added.
   * @throws {TypeError} on bad parameter types (input).
   * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with
   *                                 the given key.
   * @throws {sshpk.KeyParseError} if key was bad.
   * @throws {MissingHeaderError} if a header to be signed was specified but
   *                              was not present.
   */
  signRequest: function signRequest(request, options) {
    assert.object(request, 'request');
    assert.object(options, 'options');
    assert.optionalString(options.algorithm, 'options.algorithm');
    assert.string(options.keyId, 'options.keyId');
    assert.optionalArrayOfString(options.headers, 'options.headers');
    assert.optionalString(options.httpVersion, 'options.httpVersion');
 
    if (!request.getHeader('Date'))
      request.setHeader('Date', jsprim.rfc1123(new Date()));
    if (!options.headers)
      options.headers = ['date'];
    if (!options.httpVersion)
      options.httpVersion = '1.1';
 
    var alg = [];
    if (options.algorithm) {
      options.algorithm = options.algorithm.toLowerCase();
      alg = validateAlgorithm(options.algorithm);
    }
 
    var i;
    var stringToSign = '';
    for (i = 0; i < options.headers.length; i++) {
      if (typeof (options.headers[i]) !== 'string')
        throw new TypeError('options.headers must be an array of Strings');
 
      var h = options.headers[i].toLowerCase();
 
      if (h === 'request-line') {
        if (!options.strict) {
          /**
           * We allow headers from the older spec drafts if strict parsing isn't
           * specified in options.
           */
          stringToSign +=
            request.method + ' ' + request.path + ' HTTP/' +
            options.httpVersion;
        } else {
          /* Strict parsing doesn't allow older draft headers. */
          throw (new StrictParsingError('request-line is not a valid header ' +
            'with strict parsing enabled.'));
        }
      } else if (h === '(request-target)') {
        stringToSign +=
          '(request-target): ' + request.method.toLowerCase() + ' ' +
          request.path;
      } else {
        var value = request.getHeader(h);
        if (value === undefined || value === '') {
          throw new MissingHeaderError(h + ' was not in the request');
        }
        stringToSign += h + ': ' + value;
      }
 
      if ((i + 1) < options.headers.length)
        stringToSign += '\n';
    }
 
    /* This is just for unit tests. */
    if (request.hasOwnProperty('_stringToSign')) {
      request._stringToSign = stringToSign;
    }
 
    var signature;
    if (alg[0] === 'hmac') {
      if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
        throw (new TypeError('options.key must be a string or Buffer'));
 
      var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key);
      hmac.update(stringToSign);
      signature = hmac.digest('base64');
 
    } else {
      var key = options.key;
      if (typeof (key) === 'string' || Buffer.isBuffer(key))
        key = sshpk.parsePrivateKey(options.key);
 
      assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
        'options.key must be a sshpk.PrivateKey');
 
      if (!PK_ALGOS[key.type]) {
        throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
          'keys are not supported'));
      }
 
      if (alg[0] !== undefined && key.type !== alg[0]) {
        throw (new InvalidAlgorithmError('options.key must be a ' +
          alg[0].toUpperCase() + ' key, was given a ' +
          key.type.toUpperCase() + ' key instead'));
      }
 
      var signer = key.createSign(alg[1]);
      signer.update(stringToSign);
      var sigObj = signer.sign();
      if (!HASH_ALGOS[sigObj.hashAlgorithm]) {
        throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() +
          ' is not a supported hash algorithm'));
      }
      options.algorithm = key.type + '-' + sigObj.hashAlgorithm;
      signature = sigObj.toString();
      assert.notStrictEqual(signature, '', 'empty signature produced');
    }
 
    request.setHeader('Authorization', sprintf(AUTHZ_FMT,
                                               options.keyId,
                                               options.algorithm,
                                               options.headers.join(' '),
                                               signature));
 
    return true;
  }
 
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/utils.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/utils.js

Statements: 32.35% (11 / 34)      Branches: 0% (0 / 12)      Functions: 0% (0 / 6)      Lines: 32.35% (11 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114    1 1 1   1           1           1             1   1     1   1                                             1                                                                                                                    
// Copyright 2012 Joyent, Inc.  All rights reserved.
 
var assert = require('assert-plus');
var sshpk = require('sshpk');
var util = require('util');
 
var HASH_ALGOS = {
  'sha1': true,
  'sha256': true,
  'sha512': true
};
 
var PK_ALGOS = {
  'rsa': true,
  'dsa': true,
  'ecdsa': true
};
 
function HttpSignatureError(message, caller) {
  if (Error.captureStackTrace)
    Error.captureStackTrace(this, caller || HttpSignatureError);
 
  this.message = message;
  this.name = caller.name;
}
util.inherits(HttpSignatureError, Error);
 
function InvalidAlgorithmError(message) {
  HttpSignatureError.call(this, message, InvalidAlgorithmError);
}
util.inherits(InvalidAlgorithmError, HttpSignatureError);
 
function validateAlgorithm(algorithm) {
  var alg = algorithm.toLowerCase().split('-');
 
  if (alg.length !== 2) {
    throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' +
      'valid algorithm'));
  }
 
  if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) {
    throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' +
      'are not supported'));
  }
 
  if (!HASH_ALGOS[alg[1]]) {
    throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' +
      'supported hash algorithm'));
  }
 
  return (alg);
}
 
///--- API
 
module.exports = {
 
  HASH_ALGOS: HASH_ALGOS,
  PK_ALGOS: PK_ALGOS,
 
  HttpSignatureError: HttpSignatureError,
  InvalidAlgorithmError: InvalidAlgorithmError,
 
  validateAlgorithm: validateAlgorithm,
 
  /**
   * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
   *
   * The intent of this module is to interoperate with OpenSSL only,
   * specifically the node crypto module's `verify` method.
   *
   * @param {String} key an OpenSSH public key.
   * @return {String} PEM encoded form of the RSA public key.
   * @throws {TypeError} on bad input.
   * @throws {Error} on invalid ssh key formatted data.
   */
  sshKeyToPEM: function sshKeyToPEM(key) {
    assert.string(key, 'ssh_key');
 
    var k = sshpk.parseKey(key, 'ssh');
    return (k.toString('pem'));
  },
 
 
  /**
   * Generates an OpenSSH fingerprint from an ssh public key.
   *
   * @param {String} key an OpenSSH public key.
   * @return {String} key fingerprint.
   * @throws {TypeError} on bad input.
   * @throws {Error} if what you passed doesn't look like an ssh public key.
   */
  fingerprint: function fingerprint(key) {
    assert.string(key, 'ssh_key');
 
    var k = sshpk.parseKey(key, 'ssh');
    return (k.fingerprint('md5').toString('hex'));
  },
 
  /**
   * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
   *
   * The reverse of the above function.
   */
  pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
    assert.equal('string', typeof (pem), 'typeof pem');
 
    var k = sshpk.parseKey(pem, 'pem');
    k.comment = comment;
    return (k.toString('ssh'));
  }
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/verify.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/lib/verify.js

Statements: 25.64% (10 / 39)      Branches: 0% (0 / 16)      Functions: 0% (0 / 2)      Lines: 25.64% (10 / 39)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90    1 1 1 1   1 1 1 1 1       1                                                                                                                                                    
// Copyright 2015 Joyent, Inc.
 
var assert = require('assert-plus');
var crypto = require('crypto');
var sshpk = require('sshpk');
var utils = require('./utils');
 
var HASH_ALGOS = utils.HASH_ALGOS;
var PK_ALGOS = utils.PK_ALGOS;
var InvalidAlgorithmError = utils.InvalidAlgorithmError;
var HttpSignatureError = utils.HttpSignatureError;
var validateAlgorithm = utils.validateAlgorithm;
 
///--- Exported API
 
module.exports = {
  /**
   * Verify RSA/DSA signature against public key.  You are expected to pass in
   * an object that was returned from `parse()`.
   *
   * @param {Object} parsedSignature the object you got from `parse`.
   * @param {String} pubkey RSA/DSA private key PEM.
   * @return {Boolean} true if valid, false otherwise.
   * @throws {TypeError} if you pass in bad arguments.
   * @throws {InvalidAlgorithmError}
   */
  verifySignature: function verifySignature(parsedSignature, pubkey) {
    assert.object(parsedSignature, 'parsedSignature');
    if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey))
      pubkey = sshpk.parseKey(pubkey);
    assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key');
 
    var alg = validateAlgorithm(parsedSignature.algorithm);
    if (alg[0] === 'hmac' || alg[0] !== pubkey.type)
      return (false);
 
    var v = pubkey.createVerify(alg[1]);
    v.update(parsedSignature.signingString);
    return (v.verify(parsedSignature.params.signature, 'base64'));
  },
 
  /**
   * Verify HMAC against shared secret.  You are expected to pass in an object
   * that was returned from `parse()`.
   *
   * @param {Object} parsedSignature the object you got from `parse`.
   * @param {String} secret HMAC shared secret.
   * @return {Boolean} true if valid, false otherwise.
   * @throws {TypeError} if you pass in bad arguments.
   * @throws {InvalidAlgorithmError}
   */
  verifyHMAC: function verifyHMAC(parsedSignature, secret) {
    assert.object(parsedSignature, 'parsedHMAC');
    assert.string(secret, 'secret');
 
    var alg = validateAlgorithm(parsedSignature.algorithm);
    if (alg[0] !== 'hmac')
      return (false);
 
    var hashAlg = alg[1].toUpperCase();
 
    var hmac = crypto.createHmac(hashAlg, secret);
    hmac.update(parsedSignature.signingString);
 
    /*
     * Now double-hash to avoid leaking timing information - there's
     * no easy constant-time compare in JS, so we use this approach
     * instead. See for more info:
     * https://www.isecpartners.com/blog/2011/february/double-hmac-
     * verification.aspx
     */
    var h1 = crypto.createHmac(hashAlg, secret);
    h1.update(hmac.digest());
    h1 = h1.digest();
    var h2 = crypto.createHmac(hashAlg, secret);
    h2.update(new Buffer(parsedSignature.params.signature, 'base64'));
    h2 = h2.digest();
 
    /* Node 0.8 returns strings from .digest(). */
    if (typeof (h1) === 'string')
      return (h1 === h2);
    /* And node 0.10 lacks the .equals() method on Buffers. */
    if (Buffer.isBuffer(h1) && !h1.equals)
      return (h1.toString('binary') === h2.toString('binary'));
 
    return (h1.equals(h2));
  }
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/assert-plus/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/assert-plus/

Statements: 49.45% (45 / 91)      Branches: 17.02% (8 / 47)      Functions: 26.92% (7 / 26)      Lines: 49.45% (45 / 91)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/assert-plus/
File Statements Branches Functions Lines
assert.js 49.45% (45 / 91) 17.02% (8 / 47) 26.92% (7 / 26) 49.45% (45 / 91)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js

Statements: 49.45% (45 / 91)      Branches: 17.02% (8 / 47)      Functions: 26.92% (7 / 26)      Lines: 49.45% (45 / 91)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208      1 1 1           1         1 33     1                   1       1             1                                                                                                     1 1 1     1     1               1 11       11 11               1 11 11       11 11                     1 11 11       11 11 11                           1 11 11       11 11 11                                 1 14 1 1   13       13       1   1     1    
// Copyright (c) 2012, Mark Cavage. All rights reserved.
// Copyright 2015 Joyent, Inc.
 
var assert = require('assert');
var Stream = require('stream').Stream;
var util = require('util');
 
 
///--- Globals
 
/* JSSTYLED */
var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
 
 
///--- Internal
 
function _capitalize(str) {
    return (str.charAt(0).toUpperCase() + str.slice(1));
}
 
function _toss(name, expected, oper, arg, actual) {
    throw new assert.AssertionError({
        message: util.format('%s (%s) is required', name, expected),
        actual: (actual === undefined) ? typeof (arg) : actual(arg),
        expected: expected,
        operator: oper || '===',
        stackStartFunction: _toss.caller
    });
}
 
function _getClass(arg) {
    return (Object.prototype.toString.call(arg).slice(8, -1));
}
 
function noop() {
    // Why even bother with asserts?
}
 
 
///--- Exports
 
var types = {
    bool: {
        check: function (arg) { return typeof (arg) === 'boolean'; }
    },
    func: {
        check: function (arg) { return typeof (arg) === 'function'; }
    },
    string: {
        check: function (arg) { return typeof (arg) === 'string'; }
    },
    object: {
        check: function (arg) {
            return typeof (arg) === 'object' && arg !== null;
        }
    },
    number: {
        check: function (arg) {
            return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
        }
    },
    buffer: {
        check: function (arg) { return Buffer.isBuffer(arg); },
        operator: 'Buffer.isBuffer'
    },
    array: {
        check: function (arg) { return Array.isArray(arg); },
        operator: 'Array.isArray'
    },
    stream: {
        check: function (arg) { return arg instanceof Stream; },
        operator: 'instanceof',
        actual: _getClass
    },
    date: {
        check: function (arg) { return arg instanceof Date; },
        operator: 'instanceof',
        actual: _getClass
    },
    regexp: {
        check: function (arg) { return arg instanceof RegExp; },
        operator: 'instanceof',
        actual: _getClass
    },
    uuid: {
        check: function (arg) {
            return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
        },
        operator: 'isUUID'
    }
};
 
function _setExports(ndebug) {
    var keys = Object.keys(types);
    var out;
 
    /* re-export standard assert */
    Iif (process.env.NODE_NDEBUG) {
        out = noop;
    } else {
        out = function (arg, msg) {
            if (!arg) {
                _toss(msg, 'true', arg);
            }
        };
    }
 
    /* standard checks */
    keys.forEach(function (k) {
        Iif (ndebug) {
            out[k] = noop;
            return;
        }
        var type = types[k];
        out[k] = function (arg, msg) {
            if (!type.check(arg)) {
                _toss(msg, k, type.operator, arg, type.actual);
            }
        };
    });
 
    /* optional checks */
    keys.forEach(function (k) {
        var name = 'optional' + _capitalize(k);
        Iif (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        out[name] = function (arg, msg) {
            if (arg === undefined || arg === null) {
                return;
            }
            if (!type.check(arg)) {
                _toss(msg, k, type.operator, arg, type.actual);
            }
        };
    });
 
    /* arrayOf checks */
    keys.forEach(function (k) {
        var name = 'arrayOf' + _capitalize(k);
        Iif (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        var expected = '[' + k + ']';
        out[name] = function (arg, msg) {
            if (!Array.isArray(arg)) {
                _toss(msg, expected, type.operator, arg, type.actual);
            }
            var i;
            for (i = 0; i < arg.length; i++) {
                if (!type.check(arg[i])) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
            }
        };
    });
 
    /* optionalArrayOf checks */
    keys.forEach(function (k) {
        var name = 'optionalArrayOf' + _capitalize(k);
        Iif (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        var expected = '[' + k + ']';
        out[name] = function (arg, msg) {
            if (arg === undefined || arg === null) {
                return;
            }
            if (!Array.isArray(arg)) {
                _toss(msg, expected, type.operator, arg, type.actual);
            }
            var i;
            for (i = 0; i < arg.length; i++) {
                if (!type.check(arg[i])) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
            }
        };
    });
 
    /* re-export built-in assertions */
    Object.keys(assert).forEach(function (k) {
        if (k === 'AssertionError') {
            out[k] = assert[k];
            return;
        }
        Iif (ndebug) {
            out[k] = noop;
            return;
        }
        out[k] = assert[k];
    });
 
    /* export ourselves (for unit tests _only_) */
    out._setExports = _setExports;
 
    return out;
}
 
module.exports = _setExports(process.env.NODE_NDEBUG);
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/lib/

Statements: 26.36% (58 / 220)      Branches: 0% (0 / 76)      Functions: 0% (0 / 28)      Lines: 26.36% (58 / 220)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/lib/
File Statements Branches Functions Lines
jsprim.js 26.36% (58 / 220) 0% (0 / 76) 0% (0 / 28) 26.36% (58 / 220)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/lib/jsprim.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/lib/jsprim.js

Statements: 26.36% (58 / 220)      Branches: 0% (0 / 76)      Functions: 0% (0 / 28)      Lines: 26.36% (58 / 220)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490        1 1   1 1 1         1 1 1 1 1 1 1 1 1 1 1 1 1   1 1   1 1 1   1 1 1 1 1 1 1               1                                                                               1                                                       1               1           1                 1           1                                                 1         1                                               1                                           1         1           1                     1     1     1                         1                                   1                                                                       1               1                             1                                             1                     1                     1                       1                                                           1                                 1                                           1                                              
/*
 * lib/jsprim.js: utilities for primitive JavaScript types
 */
 
var mod_assert = require('assert');
var mod_util = require('util');
 
var mod_extsprintf = require('extsprintf');
var mod_verror = require('verror');
var mod_jsonschema = require('json-schema');
 
/*
 * Public interface
 */
exports.deepCopy = deepCopy;
exports.deepEqual = deepEqual;
exports.isEmpty = isEmpty;
exports.hasKey = hasKey;
exports.forEachKey = forEachKey;
exports.pluck = pluck;
exports.flattenObject = flattenObject;
exports.flattenIter = flattenIter;
exports.validateJsonObject = validateJsonObjectJS;
exports.validateJsonObjectJS = validateJsonObjectJS;
exports.randElt = randElt;
exports.extraProperties = extraProperties;
exports.mergeObjects = mergeObjects;
 
exports.startsWith = startsWith;
exports.endsWith = endsWith;
 
exports.iso8601 = iso8601;
exports.rfc1123 = rfc1123;
exports.parseDateTime = parseDateTime;
 
exports.hrtimediff = hrtimeDiff;
exports.hrtimeDiff = hrtimeDiff;
exports.hrtimeAccum = hrtimeAccum;
exports.hrtimeAdd = hrtimeAdd;
exports.hrtimeNanosec = hrtimeNanosec;
exports.hrtimeMicrosec = hrtimeMicrosec;
exports.hrtimeMillisec = hrtimeMillisec;
 
 
/*
 * Deep copy an acyclic *basic* Javascript object.  This only handles basic
 * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects
 * containing these.  This does *not* handle instances of other classes.
 */
function deepCopy(obj)
{
	var ret, key;
	var marker = '__deepCopy';
 
	if (obj && obj[marker])
		throw (new Error('attempted deep copy of cyclic object'));
 
	if (obj && obj.constructor == Object) {
		ret = {};
		obj[marker] = true;
 
		for (key in obj) {
			if (key == marker)
				continue;
 
			ret[key] = deepCopy(obj[key]);
		}
 
		delete (obj[marker]);
		return (ret);
	}
 
	if (obj && obj.constructor == Array) {
		ret = [];
		obj[marker] = true;
 
		for (key = 0; key < obj.length; key++)
			ret.push(deepCopy(obj[key]));
 
		delete (obj[marker]);
		return (ret);
	}
 
	/*
	 * It must be a primitive type -- just return it.
	 */
	return (obj);
}
 
function deepEqual(obj1, obj2)
{
	if (typeof (obj1) != typeof (obj2))
		return (false);
 
	if (obj1 === null || obj2 === null || typeof (obj1) != 'object')
		return (obj1 === obj2);
 
	if (obj1.constructor != obj2.constructor)
		return (false);
 
	var k;
	for (k in obj1) {
		if (!obj2.hasOwnProperty(k))
			return (false);
 
		if (!deepEqual(obj1[k], obj2[k]))
			return (false);
	}
 
	for (k in obj2) {
		if (!obj1.hasOwnProperty(k))
			return (false);
	}
 
	return (true);
}
 
function isEmpty(obj)
{
	var key;
	for (key in obj)
		return (false);
	return (true);
}
 
function hasKey(obj, key)
{
	mod_assert.equal(typeof (key), 'string');
	return (Object.prototype.hasOwnProperty.call(obj, key));
}
 
function forEachKey(obj, callback)
{
	for (var key in obj) {
		if (hasKey(obj, key)) {
			callback(key, obj[key]);
		}
	}
}
 
function pluck(obj, key)
{
	mod_assert.equal(typeof (key), 'string');
	return (pluckv(obj, key));
}
 
function pluckv(obj, key)
{
	if (obj === null || typeof (obj) !== 'object')
		return (undefined);
 
	if (obj.hasOwnProperty(key))
		return (obj[key]);
 
	var i = key.indexOf('.');
	if (i == -1)
		return (undefined);
 
	var key1 = key.substr(0, i);
	if (!obj.hasOwnProperty(key1))
		return (undefined);
 
	return (pluckv(obj[key1], key.substr(i + 1)));
}
 
/*
 * Invoke callback(row) for each entry in the array that would be returned by
 * flattenObject(data, depth).  This is just like flattenObject(data,
 * depth).forEach(callback), except that the intermediate array is never
 * created.
 */
function flattenIter(data, depth, callback)
{
	doFlattenIter(data, depth, [], callback);
}
 
function doFlattenIter(data, depth, accum, callback)
{
	var each;
	var key;
 
	if (depth === 0) {
		each = accum.slice(0);
		each.push(data);
		callback(each);
		return;
	}
 
	mod_assert.ok(data !== null);
	mod_assert.equal(typeof (data), 'object');
	mod_assert.equal(typeof (depth), 'number');
	mod_assert.ok(depth >= 0);
 
	for (key in data) {
		each = accum.slice(0);
		each.push(key);
		doFlattenIter(data[key], depth - 1, each, callback);
	}
}
 
function flattenObject(data, depth)
{
	if (depth === 0)
		return ([ data ]);
 
	mod_assert.ok(data !== null);
	mod_assert.equal(typeof (data), 'object');
	mod_assert.equal(typeof (depth), 'number');
	mod_assert.ok(depth >= 0);
 
	var rv = [];
	var key;
 
	for (key in data) {
		flattenObject(data[key], depth - 1).forEach(function (p) {
			rv.push([ key ].concat(p));
		});
	}
 
	return (rv);
}
 
function startsWith(str, prefix)
{
	return (str.substr(0, prefix.length) == prefix);
}
 
function endsWith(str, suffix)
{
	return (str.substr(
	    str.length - suffix.length, suffix.length) == suffix);
}
 
function iso8601(d)
{
	if (typeof (d) == 'number')
		d = new Date(d);
	mod_assert.ok(d.constructor === Date);
	return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ',
	    d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(),
	    d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(),
	    d.getUTCMilliseconds()));
}
 
var RFC1123_MONTHS = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var RFC1123_DAYS = [
    'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
 
function rfc1123(date) {
	return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT',
	    RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(),
	    RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(),
	    date.getUTCHours(), date.getUTCMinutes(),
	    date.getUTCSeconds()));
}
 
/*
 * Parses a date expressed as a string, as either a number of milliseconds since
 * the epoch or any string format that Date accepts, giving preference to the
 * former where these two sets overlap (e.g., small numbers).
 */
function parseDateTime(str)
{
	/*
	 * This is irritatingly implicit, but significantly more concise than
	 * alternatives.  The "+str" will convert a string containing only a
	 * number directly to a Number, or NaN for other strings.  Thus, if the
	 * conversion succeeds, we use it (this is the milliseconds-since-epoch
	 * case).  Otherwise, we pass the string directly to the Date
	 * constructor to parse.
	 */
	var numeric = +str;
	if (!isNaN(numeric)) {
		return (new Date(numeric));
	} else {
		return (new Date(str));
	}
}
 
function validateJsonObjectJS(schema, input)
{
	var report = mod_jsonschema.validate(input, schema);
 
	if (report.errors.length === 0)
		return (null);
 
	/* Currently, we only do anything useful with the first error. */
	var error = report.errors[0];
 
	/* The failed property is given by a URI with an irrelevant prefix. */
	var propname = error['property'];
	var reason = error['message'].toLowerCase();
	var i, j;
 
	/*
	 * There's at least one case where the property error message is
	 * confusing at best.  We work around this here.
	 */
	if ((i = reason.indexOf('the property ')) != -1 &&
	    (j = reason.indexOf(' is not defined in the schema and the ' +
	    'schema does not allow additional properties')) != -1) {
		i += 'the property '.length;
		if (propname === '')
			propname = reason.substr(i, j - i);
		else
			propname = propname + '.' + reason.substr(i, j - i);
 
		reason = 'unsupported property';
	}
 
	var rv = new mod_verror.VError('property "%s": %s', propname, reason);
	rv.jsv_details = error;
	return (rv);
}
 
function randElt(arr)
{
	mod_assert.ok(Array.isArray(arr) && arr.length > 0,
	    'randElt argument must be a non-empty array');
 
	return (arr[Math.floor(Math.random() * arr.length)]);
}
 
function assertHrtime(a)
{
	mod_assert.ok(a[0] >= 0 && a[1] >= 0,
	    'negative numbers not allowed in hrtimes');
	mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow');
}
 
/*
 * Compute the time elapsed between hrtime readings A and B, where A is later
 * than B.  hrtime readings come from Node's process.hrtime().  There is no
 * defined way to represent negative deltas, so it's illegal to diff B from A
 * where the time denoted by B is later than the time denoted by A.  If this
 * becomes valuable, we can define a representation and extend the
 * implementation to support it.
 */
function hrtimeDiff(a, b)
{
	assertHrtime(a);
	assertHrtime(b);
	mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]),
	    'negative differences not allowed');
 
	var rv = [ a[0] - b[0], 0 ];
 
	if (a[1] >= b[1]) {
		rv[1] = a[1] - b[1];
	} else {
		rv[0]--;
		rv[1] = 1e9 - (b[1] - a[1]);
	}
 
	return (rv);
}
 
/*
 * Convert a hrtime reading from the array format returned by Node's
 * process.hrtime() into a scalar number of nanoseconds.
 */
function hrtimeNanosec(a)
{
	assertHrtime(a);
 
	return (Math.floor(a[0] * 1e9 + a[1]));
}
 
/*
 * Convert a hrtime reading from the array format returned by Node's
 * process.hrtime() into a scalar number of microseconds.
 */
function hrtimeMicrosec(a)
{
	assertHrtime(a);
 
	return (Math.floor(a[0] * 1e6 + a[1] / 1e3));
}
 
/*
 * Convert a hrtime reading from the array format returned by Node's
 * process.hrtime() into a scalar number of milliseconds.
 */
function hrtimeMillisec(a)
{
	assertHrtime(a);
 
	return (Math.floor(a[0] * 1e3 + a[1] / 1e6));
}
 
/*
 * Add two hrtime readings A and B, overwriting A with the result of the
 * addition.  This function is useful for accumulating several hrtime intervals
 * into a counter.  Returns A.
 */
function hrtimeAccum(a, b)
{
	assertHrtime(a);
	assertHrtime(b);
 
	/*
	 * Accumulate the nanosecond component.
	 */
	a[1] += b[1];
	if (a[1] >= 1e9) {
		/*
		 * The nanosecond component overflowed, so carry to the seconds
		 * field.
		 */
		a[0]++;
		a[1] -= 1e9;
	}
 
	/*
	 * Accumulate the seconds component.
	 */
	a[0] += b[0];
 
	return (a);
}
 
/*
 * Add two hrtime readings A and B, returning the result as a new hrtime array.
 * Does not modify either input argument.
 */
function hrtimeAdd(a, b)
{
	assertHrtime(a);
 
	var rv = [ a[0], a[1] ];
 
	return (hrtimeAccum(rv, b));
}
 
 
/*
 * Check an object for unexpected properties.  Accepts the object to check, and
 * an array of allowed property names (strings).  Returns an array of key names
 * that were found on the object, but did not appear in the list of allowed
 * properties.  If no properties were found, the returned array will be of
 * zero length.
 */
function extraProperties(obj, allowed)
{
	mod_assert.ok(typeof (obj) === 'object' && obj !== null,
	    'obj argument must be a non-null object');
	mod_assert.ok(Array.isArray(allowed),
	    'allowed argument must be an array of strings');
	for (var i = 0; i < allowed.length; i++) {
		mod_assert.ok(typeof (allowed[i]) === 'string',
		    'allowed argument must be an array of strings');
	}
 
	return (Object.keys(obj).filter(function (key) {
		return (allowed.indexOf(key) === -1);
	}));
}
 
/*
 * Given three sets of properties "provided" (may be undefined), "overrides"
 * (required), and "defaults" (may be undefined), construct an object containing
 * the union of these sets with "overrides" overriding "provided", and
 * "provided" overriding "defaults".  None of the input objects are modified.
 */
function mergeObjects(provided, overrides, defaults)
{
	var rv, k;
 
	rv = {};
	if (defaults) {
		for (k in defaults)
			rv[k] = defaults[k];
	}
 
	if (provided) {
		for (k in provided)
			rv[k] = provided[k];
	}
 
	if (overrides) {
		for (k in overrides)
			rv[k] = overrides[k];
	}
 
	return (rv);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/extsprintf/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/extsprintf/lib/

Statements: 8.11% (6 / 74)      Branches: 0% (0 / 46)      Functions: 0% (0 / 3)      Lines: 8.11% (6 / 74)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/extsprintf/lib/
File Statements Branches Functions Lines
extsprintf.js 8.11% (6 / 74) 0% (0 / 46) 0% (0 / 3) 8.11% (6 / 74)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/extsprintf/lib/extsprintf.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/extsprintf/lib/extsprintf.js

Statements: 8.11% (6 / 74)      Branches: 0% (0 / 46)      Functions: 0% (0 / 3)      Lines: 8.11% (6 / 74)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168        1 1         1                                       1                                                                                                                                                                                                     1                                   1                                        
/*
 * extsprintf.js: extended POSIX-style sprintf
 */
 
var mod_assert = require('assert');
var mod_util = require('util');
 
/*
 * Public interface
 */
exports.sprintf = jsSprintf;
 
/*
 * Stripped down version of s[n]printf(3c).  We make a best effort to throw an
 * exception when given a format string we don't understand, rather than
 * ignoring it, so that we won't break existing programs if/when we go implement
 * the rest of this.
 *
 * This implementation currently supports specifying
 *	- field alignment ('-' flag),
 * 	- zero-pad ('0' flag)
 *	- always show numeric sign ('+' flag),
 *	- field width
 *	- conversions for strings, decimal integers, and floats (numbers).
 *	- argument size specifiers.  These are all accepted but ignored, since
 *	  Javascript has no notion of the physical size of an argument.
 *
 * Everything else is currently unsupported, most notably precision, unsigned
 * numbers, non-decimal numbers, and characters.
 */
function jsSprintf(fmt)
{
	var regex = [
	    '([^%]*)',				/* normal text */
	    '%',				/* start of format */
	    '([\'\\-+ #0]*?)',			/* flags (optional) */
	    '([1-9]\\d*)?',			/* width (optional) */
	    '(\\.([1-9]\\d*))?',		/* precision (optional) */
	    '[lhjztL]*?',			/* length mods (ignored) */
	    '([diouxXfFeEgGaAcCsSp%jr])'	/* conversion */
	].join('');
 
	var re = new RegExp(regex);
	var args = Array.prototype.slice.call(arguments, 1);
	var flags, width, precision, conversion;
	var left, pad, sign, arg, match;
	var ret = '';
	var argn = 1;
 
	mod_assert.equal('string', typeof (fmt));
 
	while ((match = re.exec(fmt)) !== null) {
		ret += match[1];
		fmt = fmt.substring(match[0].length);
 
		flags = match[2] || '';
		width = match[3] || 0;
		precision = match[4] || '';
		conversion = match[6];
		left = false;
		sign = false;
		pad = ' ';
 
		if (conversion == '%') {
			ret += '%';
			continue;
		}
 
		if (args.length === 0)
			throw (new Error('too few args to sprintf'));
 
		arg = args.shift();
		argn++;
 
		if (flags.match(/[\' #]/))
			throw (new Error(
			    'unsupported flags: ' + flags));
 
		if (precision.length > 0)
			throw (new Error(
			    'non-zero precision not supported'));
 
		if (flags.match(/-/))
			left = true;
 
		if (flags.match(/0/))
			pad = '0';
 
		if (flags.match(/\+/))
			sign = true;
 
		switch (conversion) {
		case 's':
			if (arg === undefined || arg === null)
				throw (new Error('argument ' + argn +
				    ': attempted to print undefined or null ' +
				    'as a string'));
			ret += doPad(pad, width, left, arg.toString());
			break;
 
		case 'd':
			arg = Math.floor(arg);
			/*jsl:fallthru*/
		case 'f':
			sign = sign && arg > 0 ? '+' : '';
			ret += sign + doPad(pad, width, left,
			    arg.toString());
			break;
 
		case 'j': /* non-standard */
			if (width === 0)
				width = 10;
			ret += mod_util.inspect(arg, false, width);
			break;
 
		case 'r': /* non-standard */
			ret += dumpException(arg);
			break;
 
		default:
			throw (new Error('unsupported conversion: ' +
			    conversion));
		}
	}
 
	ret += fmt;
	return (ret);
}
 
function doPad(chr, width, left, str)
{
	var ret = str;
 
	while (ret.length < width) {
		if (left)
			ret += chr;
		else
			ret = chr + ret;
	}
 
	return (ret);
}
 
/*
 * This function dumps long stack traces for exceptions having a cause() method.
 * See node-verror for an example.
 */
function dumpException(ex)
{
	var ret;
 
	if (!(ex instanceof Error))
		throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
 
	/* Note that V8 prepends "ex.stack" with ex.toString(). */
	ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
 
	if (ex.cause && typeof (ex.cause) === 'function') {
		var cex = ex.cause();
		if (cex) {
			ret += '\nCaused by: ' + dumpException(cex);
		}
	}
 
	return (ret);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/json-schema/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/json-schema/lib/

Statements: 12.41% (18 / 145)      Branches: 2.55% (5 / 196)      Functions: 15.38% (2 / 13)      Lines: 12.68% (18 / 142)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/json-schema/lib/
File Statements Branches Functions Lines
validate.js 12.41% (18 / 145) 2.55% (5 / 196) 15.38% (2 / 13) 12.68% (18 / 142)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/json-schema/lib/validate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/json-schema/lib/validate.js

Statements: 12.41% (18 / 145)      Branches: 2.55% (5 / 196)      Functions: 15.38% (2 / 13)      Lines: 12.68% (18 / 142)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275                              1 1         1       1           1 1 1               1 1                             1                   1         1         1       1                                         1                                                                                                                                                                                                         1                                                                                                                     1                 1      
/**
 * JSONSchema Validator - Validates JavaScript objects using JSON Schemas
 *	(http://www.json.com/json-schema-proposal/)
 *
 * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
 * Licensed under the MIT (MIT-LICENSE.txt) license.
To use the validator call the validate function with an instance object and an optional schema object.
If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
that schema will be used to validate and the schema parameter is not necessary (if both exist,
both validations will occur).
The validate method will return an array of validation errors. If there are no errors, then an
empty list will be returned. A validation error will have two properties:
"property" which indicates which property had the error
"message" which indicates what the error was
 */
(function (root, factory) {
    Iif (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], function () {
            return factory();
        });
    } else Eif (typeof module === 'object' && module.exports) {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals
        root.jsonSchema = factory();
    }
}(this, function () {// setup primitive classes to be JSON Schema types
var exports = validate
exports.Integer = {type:"integer"};
var primitiveConstructors = {
	String: String,
	Boolean: Boolean,
	Number: Number,
	Object: Object,
	Array: Array,
	Date: Date
}
exports.validate = validate;
function validate(/*Any*/instance,/*Object*/schema) {
		// Summary:
		//  	To use the validator call JSONSchema.validate with an instance object and an optional schema object.
		// 		If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
		// 		that schema will be used to validate and the schema parameter is not necessary (if both exist,
		// 		both validations will occur).
		// 		The validate method will return an object with two properties:
		// 			valid: A boolean indicating if the instance is valid by the schema
		// 			errors: An array of validation errors. If there are no errors, then an
		// 					empty list will be returned. A validation error will have two properties:
		// 						property: which indicates which property had the error
		// 						message: which indicates what the error was
		//
		return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false});
	};
exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) {
		// Summary:
		// 		The checkPropertyChange method will check to see if an value can legally be in property with the given schema
		// 		This is slightly different than the validate method in that it will fail if the schema is readonly and it will
		// 		not check for self-validation, it is assumed that the passed in value is already internally valid.
		// 		The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for
		// 		information.
		//
		return validate(value, schema, {changing: property || "property"});
	};
var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) {
 
	if (!options) options = {};
	var _changing = options.changing;
 
	function getType(schema){
		return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase());
	}
	var errors = [];
	// validate a value against a property definition
	function checkProp(value, schema, path,i){
 
		var l;
		path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i;
		function addError(message){
			errors.push({property:path,message:message});
		}
 
		if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){
			if(typeof schema == 'function'){
				if(!(value instanceof schema)){
					addError("is not an instance of the class/constructor " + schema.name);
				}
			}else if(schema){
				addError("Invalid schema/property definition " + schema);
			}
			return null;
		}
		if(_changing && schema.readonly){
			addError("is a readonly field, it can not be changed");
		}
		if(schema['extends']){ // if it extends another schema, it must pass that schema as well
			checkProp(value,schema['extends'],path,i);
		}
		// validate a value against a type definition
		function checkType(type,value){
			if(type){
				if(typeof type == 'string' && type != 'any' &&
						(type == 'null' ? value !== null : typeof value != type) &&
						!(value instanceof Array && type == 'array') &&
						!(value instanceof Date && type == 'date') &&
						!(type == 'integer' && value%1===0)){
					return [{property:path,message:(typeof value) + " value found, but a " + type + " is required"}];
				}
				if(type instanceof Array){
					var unionErrors=[];
					for(var j = 0; j < type.length; j++){ // a union type
						if(!(unionErrors=checkType(type[j],value)).length){
							break;
						}
					}
					if(unionErrors.length){
						return unionErrors;
					}
				}else if(typeof type == 'object'){
					var priorErrors = errors;
					errors = [];
					checkProp(value,type,path);
					var theseErrors = errors;
					errors = priorErrors;
					return theseErrors;
				}
			}
			return [];
		}
		if(value === undefined){
			if(schema.required){
				addError("is missing and it is required");
			}
		}else{
			errors = errors.concat(checkType(getType(schema),value));
			if(schema.disallow && !checkType(schema.disallow,value).length){
				addError(" disallowed value was matched");
			}
			if(value !== null){
				if(value instanceof Array){
					if(schema.items){
						var itemsIsArray = schema.items instanceof Array;
						var propDef = schema.items;
						for (i = 0, l = value.length; i < l; i += 1) {
							if (itemsIsArray)
								propDef = schema.items[i];
							if (options.coerce)
								value[i] = options.coerce(value[i], propDef);
							errors.concat(checkProp(value[i],propDef,path,i));
						}
					}
					if(schema.minItems && value.length < schema.minItems){
						addError("There must be a minimum of " + schema.minItems + " in the array");
					}
					if(schema.maxItems && value.length > schema.maxItems){
						addError("There must be a maximum of " + schema.maxItems + " in the array");
					}
				}else if(schema.properties || schema.additionalProperties){
					errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties));
				}
				if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){
					addError("does not match the regex pattern " + schema.pattern);
				}
				if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){
					addError("may only be " + schema.maxLength + " characters long");
				}
				if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){
					addError("must be at least " + schema.minLength + " characters long");
				}
				if(typeof schema.minimum !== undefined && typeof value == typeof schema.minimum &&
						schema.minimum > value){
					addError("must have a minimum value of " + schema.minimum);
				}
				if(typeof schema.maximum !== undefined && typeof value == typeof schema.maximum &&
						schema.maximum < value){
					addError("must have a maximum value of " + schema.maximum);
				}
				if(schema['enum']){
					var enumer = schema['enum'];
					l = enumer.length;
					var found;
					for(var j = 0; j < l; j++){
						if(enumer[j]===value){
							found=1;
							break;
						}
					}
					if(!found){
						addError("does not have a value in the enumeration " + enumer.join(", "));
					}
				}
				if(typeof schema.maxDecimal == 'number' &&
					(value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){
					addError("may only have " + schema.maxDecimal + " digits of decimal places");
				}
			}
		}
		return null;
	}
	// validate an object against a schema
	function checkObj(instance,objTypeDef,path,additionalProp){
 
		if(typeof objTypeDef =='object'){
			if(typeof instance != 'object' || instance instanceof Array){
				errors.push({property:path,message:"an object is required"});
			}
			
			for(var i in objTypeDef){ 
				if(objTypeDef.hasOwnProperty(i)){
					var value = instance[i];
					// skip _not_ specified properties
					if (value === undefined && options.existingOnly) continue;
					var propDef = objTypeDef[i];
					// set default
					if(value === undefined && propDef["default"]){
						value = instance[i] = propDef["default"];
					}
					if(options.coerce && i in instance){
						value = instance[i] = options.coerce(value, propDef);
					}
					checkProp(value,propDef,path,i);
				}
			}
		}
		for(i in instance){
			if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){
				if (options.filter) {
					delete instance[i];
					continue;
				} else {
					errors.push({property:path,message:(typeof value) + "The property " + i +
						" is not defined in the schema and the schema does not allow additional properties"});
				}
			}
			var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
			if(requires && !(requires in instance)){
				errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"});
			}
			value = instance[i];
			if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){
				if(options.coerce){
					value = instance[i] = options.coerce(value, additionalProp);
				}
				checkProp(value,additionalProp,path,i);
			}
			if(!_changing && value && value.$schema){
				errors = errors.concat(checkProp(value,value.$schema,path,i));
			}
		}
		return errors;
	}
	if(schema){
		checkProp(instance,schema,'',_changing || '');
	}
	if(!_changing && instance && instance.$schema){
		checkProp(instance,instance.$schema,'','');
	}
	return {valid:!errors.length,errors:errors};
};
exports.mustBeValid = function(result){
	//	summary:
	//		This checks to ensure that the result is valid and will throw an appropriate error message if it is not
	// result: the result returned from checkPropertyChange or validate
	if(!result.valid){
		throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n"));
	}
}
 
return exports;
}));
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/lib/

Statements: 24.66% (18 / 73)      Branches: 0% (0 / 54)      Functions: 0% (0 / 7)      Lines: 24.66% (18 / 73)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/lib/
File Statements Branches Functions Lines
verror.js 24.66% (18 / 73) 0% (0 / 54) 0% (0 / 7) 24.66% (18 / 73)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/lib/verror.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/lib/verror.js

Statements: 24.66% (18 / 73)      Branches: 0% (0 / 54)      Functions: 0% (0 / 7)      Lines: 24.66% (18 / 73)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159        1 1   1         1 1 1           1                                                                           1 1   1                   1                       1                 1                 1                                                                 1 1     1                       1                
/*
 * verror.js: richer JavaScript errors
 */
 
var mod_assert = require('assert');
var mod_util = require('util');
 
var mod_extsprintf = require('extsprintf');
 
/*
 * Public interface
 */
exports.VError = VError;
exports.WError = WError;
exports.MultiError = MultiError;
 
/*
 * Like JavaScript's built-in Error class, but supports a "cause" argument and a
 * printf-style message.  The cause argument can be null.
 */
function VError(options)
{
	var args, causedBy, ctor, tailmsg;
 
	if (options instanceof Error || typeof (options) === 'object') {
		args = Array.prototype.slice.call(arguments, 1);
	} else {
		args = Array.prototype.slice.call(arguments, 0);
		options = undefined;
	}
 
	tailmsg = args.length > 0 ?
	    mod_extsprintf.sprintf.apply(null, args) : '';
	this.jse_shortmsg = tailmsg;
	this.jse_summary = tailmsg;
 
	if (options) {
		causedBy = options.cause;
 
		if (!causedBy || !(options.cause instanceof Error))
			causedBy = options;
 
		if (causedBy && (causedBy instanceof Error)) {
			this.jse_cause = causedBy;
			this.jse_summary += ': ' + causedBy.message;
		}
	}
 
	this.message = this.jse_summary;
	Error.call(this, this.jse_summary);
 
	if (Error.captureStackTrace) {
		ctor = options ? options.constructorOpt : undefined;
		ctor = ctor || arguments.callee;
		Error.captureStackTrace(this, ctor);
	}
}
 
mod_util.inherits(VError, Error);
VError.prototype.name = 'VError';
 
VError.prototype.toString = function ve_toString()
{
	var str = (this.hasOwnProperty('name') && this.name ||
		this.constructor.name || this.constructor.prototype.name);
	if (this.message)
		str += ': ' + this.message;
 
	return (str);
};
 
VError.prototype.cause = function ve_cause()
{
	return (this.jse_cause);
};
 
 
/*
 * Represents a collection of errors for the purpose of consumers that generally
 * only deal with one error.  Callers can extract the individual errors
 * contained in this object, but may also just treat it as a normal single
 * error, in which case a summary message will be printed.
 */
function MultiError(errors)
{
	mod_assert.ok(errors.length > 0);
	this.ase_errors = errors;
 
	VError.call(this, errors[0], 'first of %d error%s',
	    errors.length, errors.length == 1 ? '' : 's');
}
 
mod_util.inherits(MultiError, VError);
 
 
 
/*
 * Like JavaScript's built-in Error class, but supports a "cause" argument which
 * is wrapped, not "folded in" as with VError.	Accepts a printf-style message.
 * The cause argument can be null.
 */
function WError(options)
{
	Error.call(this);
 
	var args, cause, ctor;
	if (typeof (options) === 'object') {
		args = Array.prototype.slice.call(arguments, 1);
	} else {
		args = Array.prototype.slice.call(arguments, 0);
		options = undefined;
	}
 
	if (args.length > 0) {
		this.message = mod_extsprintf.sprintf.apply(null, args);
	} else {
		this.message = '';
	}
 
	if (options) {
		if (options instanceof Error) {
			cause = options;
		} else {
			cause = options.cause;
			ctor = options.constructorOpt;
		}
	}
 
	Error.captureStackTrace(this, ctor || this.constructor);
	if (cause)
		this.cause(cause);
 
}
 
mod_util.inherits(WError, Error);
WError.prototype.name = 'WError';
 
 
WError.prototype.toString = function we_toString()
{
	var str = (this.hasOwnProperty('name') && this.name ||
		this.constructor.name || this.constructor.prototype.name);
	if (this.message)
		str += ': ' + this.message;
	if (this.we_cause && this.we_cause.message)
		str += '; caused by ' + this.we_cause.toString();
 
	return (str);
};
 
WError.prototype.cause = function we_cause(c)
{
	if (c instanceof Error)
		this.we_cause = c;
 
	return (this.we_cause);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/

Statements: 19.15% (307 / 1603)      Branches: 0% (0 / 667)      Functions: 0.7% (1 / 142)      Lines: 19.21% (307 / 1598)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/
File Statements Branches Functions Lines
algs.js 100% (7 / 7) 100% (0 / 0) 100% (0 / 0) 100% (7 / 7)
certificate.js 14.05% (34 / 242) 0% (0 / 125) 0% (0 / 20) 14.05% (34 / 242)
dhe.js 14.36% (28 / 195) 0% (0 / 76) 0% (0 / 15) 14.66% (28 / 191)
ed-compat.js 28.57% (16 / 56) 0% (0 / 20) 0% (0 / 8) 28.57% (16 / 56)
errors.js 26.32% (15 / 57) 0% (0 / 16) 0% (0 / 6) 26.32% (15 / 57)
fingerprint.js 21.05% (20 / 95) 0% (0 / 39) 0% (0 / 10) 21.28% (20 / 94)
identity.js 23.95% (40 / 167) 0% (0 / 85) 5.56% (1 / 18) 23.95% (40 / 167)
index.js 100% (8 / 8) 100% (0 / 0) 100% (0 / 0) 100% (8 / 8)
key.js 21.11% (38 / 180) 0% (0 / 85) 0% (0 / 12) 21.11% (38 / 180)
private-key.js 26.53% (39 / 147) 0% (0 / 57) 0% (0 / 11) 26.53% (39 / 147)
signature.js 12.96% (21 / 162) 0% (0 / 65) 0% (0 / 10) 12.96% (21 / 162)
ssh-buffer.js 24.21% (23 / 95) 0% (0 / 10) 0% (0 / 21) 24.21% (23 / 95)
utils.js 9.38% (18 / 192) 0% (0 / 89) 0% (0 / 11) 9.38% (18 / 192)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/algs.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/algs.js

Statements: 100% (7 / 7)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (7 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170    1                                     1   1                             1   1                       1                                                                                                                                                                                                                           1              
// Copyright 2015 Joyent, Inc.
 
var algInfo = {
	'dsa': {
		parts: ['p', 'q', 'g', 'y'],
		sizePart: 'p'
	},
	'rsa': {
		parts: ['e', 'n'],
		sizePart: 'n'
	},
	'ecdsa': {
		parts: ['curve', 'Q'],
		sizePart: 'Q'
	},
	'ed25519': {
		parts: ['R'],
		normalize: false,
		sizePart: 'R'
	}
};
algInfo['curve25519'] = algInfo['ed25519'];
 
var algPrivInfo = {
	'dsa': {
		parts: ['p', 'q', 'g', 'y', 'x']
	},
	'rsa': {
		parts: ['n', 'e', 'd', 'iqmp', 'p', 'q']
	},
	'ecdsa': {
		parts: ['curve', 'Q', 'd']
	},
	'ed25519': {
		parts: ['R', 'r'],
		normalize: false
	}
};
algPrivInfo['curve25519'] = algPrivInfo['ed25519'];
 
var hashAlgs = {
	'md5': true,
	'sha1': true,
	'sha256': true,
	'sha384': true,
	'sha512': true
};
 
/*
 * Taken from
 * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf
 */
var curves = {
	'nistp256': {
		size: 256,
		pkcs8oid: '1.2.840.10045.3.1.7',
		p: new Buffer(('00' +
		    'ffffffff 00000001 00000000 00000000' +
		    '00000000 ffffffff ffffffff ffffffff').
		    replace(/ /g, ''), 'hex'),
		a: new Buffer(('00' +
		    'FFFFFFFF 00000001 00000000 00000000' +
		    '00000000 FFFFFFFF FFFFFFFF FFFFFFFC').
		    replace(/ /g, ''), 'hex'),
		b: new Buffer((
		    '5ac635d8 aa3a93e7 b3ebbd55 769886bc' +
		    '651d06b0 cc53b0f6 3bce3c3e 27d2604b').
		    replace(/ /g, ''), 'hex'),
		s: new Buffer(('00' +
		    'c49d3608 86e70493 6a6678e1 139d26b7' +
		    '819f7e90').
		    replace(/ /g, ''), 'hex'),
		n: new Buffer(('00' +
		    'ffffffff 00000000 ffffffff ffffffff' +
		    'bce6faad a7179e84 f3b9cac2 fc632551').
		    replace(/ /g, ''), 'hex'),
		G: new Buffer(('04' +
		    '6b17d1f2 e12c4247 f8bce6e5 63a440f2' +
		    '77037d81 2deb33a0 f4a13945 d898c296' +
		    '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' +
		    '2bce3357 6b315ece cbb64068 37bf51f5').
		    replace(/ /g, ''), 'hex')
	},
	'nistp384': {
		size: 384,
		pkcs8oid: '1.3.132.0.34',
		p: new Buffer(('00' +
		    'ffffffff ffffffff ffffffff ffffffff' +
		    'ffffffff ffffffff ffffffff fffffffe' +
		    'ffffffff 00000000 00000000 ffffffff').
		    replace(/ /g, ''), 'hex'),
		a: new Buffer(('00' +
		    'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
		    'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' +
		    'FFFFFFFF 00000000 00000000 FFFFFFFC').
		    replace(/ /g, ''), 'hex'),
		b: new Buffer((
		    'b3312fa7 e23ee7e4 988e056b e3f82d19' +
		    '181d9c6e fe814112 0314088f 5013875a' +
		    'c656398d 8a2ed19d 2a85c8ed d3ec2aef').
		    replace(/ /g, ''), 'hex'),
		s: new Buffer(('00' +
		    'a335926a a319a27a 1d00896a 6773a482' +
		    '7acdac73').
		    replace(/ /g, ''), 'hex'),
		n: new Buffer(('00' +
		    'ffffffff ffffffff ffffffff ffffffff' +
		    'ffffffff ffffffff c7634d81 f4372ddf' +
		    '581a0db2 48b0a77a ecec196a ccc52973').
		    replace(/ /g, ''), 'hex'),
		G: new Buffer(('04' +
		    'aa87ca22 be8b0537 8eb1c71e f320ad74' +
		    '6e1d3b62 8ba79b98 59f741e0 82542a38' +
		    '5502f25d bf55296c 3a545e38 72760ab7' +
		    '3617de4a 96262c6f 5d9e98bf 9292dc29' +
		    'f8f41dbd 289a147c e9da3113 b5f0b8c0' +
		    '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f').
		    replace(/ /g, ''), 'hex')
	},
	'nistp521': {
		size: 521,
		pkcs8oid: '1.3.132.0.35',
		p: new Buffer((
		    '01ffffff ffffffff ffffffff ffffffff' +
		    'ffffffff ffffffff ffffffff ffffffff' +
		    'ffffffff ffffffff ffffffff ffffffff' +
		    'ffffffff ffffffff ffffffff ffffffff' +
		    'ffff').replace(/ /g, ''), 'hex'),
		a: new Buffer(('01FF' +
		    'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
		    'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
		    'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
		    'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC').
		    replace(/ /g, ''), 'hex'),
		b: new Buffer(('51' +
		    '953eb961 8e1c9a1f 929a21a0 b68540ee' +
		    'a2da725b 99b315f3 b8b48991 8ef109e1' +
		    '56193951 ec7e937b 1652c0bd 3bb1bf07' +
		    '3573df88 3d2c34f1 ef451fd4 6b503f00').
		    replace(/ /g, ''), 'hex'),
		s: new Buffer(('00' +
		    'd09e8800 291cb853 96cc6717 393284aa' +
		    'a0da64ba').replace(/ /g, ''), 'hex'),
		n: new Buffer(('01ff' +
		    'ffffffff ffffffff ffffffff ffffffff' +
		    'ffffffff ffffffff ffffffff fffffffa' +
		    '51868783 bf2f966b 7fcc0148 f709a5d0' +
		    '3bb5c9b8 899c47ae bb6fb71e 91386409').
		    replace(/ /g, ''), 'hex'),
		G: new Buffer(('04' +
		    '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' +
		         '9c648139 053fb521 f828af60 6b4d3dba' +
		         'a14b5e77 efe75928 fe1dc127 a2ffa8de' +
		         '3348b3c1 856a429b f97e7e31 c2e5bd66' +
		    '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' +
		         '98f54449 579b4468 17afbd17 273e662c' +
		         '97ee7299 5ef42640 c550b901 3fad0761' +
		         '353c7086 a272c240 88be9476 9fd16650').
		    replace(/ /g, ''), 'hex')
	}
};
 
module.exports = {
	info: algInfo,
	privInfo: algPrivInfo,
	hashAlgs: hashAlgs,
	curves: curves
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/certificate.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/certificate.js

Statements: 14.05% (34 / 242)      Branches: 0% (0 / 125)      Functions: 0% (0 / 20)      Lines: 14.05% (34 / 242)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379    1   1 1 1 1 1 1 1 1 1 1 1   1 1 1 1   1 1   1                                                               1   1                   1           1                       1                             1             1                         1                             1                                 1                                                                                                                                                                                         1                                                                                                                                                                                         1                                                 1               1   1        
// Copyright 2016 Joyent, Inc.
 
module.exports = Certificate;
 
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors');
var util = require('util');
var utils = require('./utils');
var Key = require('./key');
var PrivateKey = require('./private-key');
var Identity = require('./identity');
 
var formats = {};
formats['openssh'] = require('./formats/openssh-cert');
formats['x509'] = require('./formats/x509');
formats['pem'] = require('./formats/x509-pem');
 
var CertificateParseError = errs.CertificateParseError;
var InvalidAlgorithmError = errs.InvalidAlgorithmError;
 
function Certificate(opts) {
	assert.object(opts, 'options');
	assert.arrayOfObject(opts.subjects, 'options.subjects');
	utils.assertCompatible(opts.subjects[0], Identity, [1, 0],
	    'options.subjects');
	utils.assertCompatible(opts.subjectKey, Key, [1, 0],
	    'options.subjectKey');
	utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer');
	if (opts.issuerKey !== undefined) {
		utils.assertCompatible(opts.issuerKey, Key, [1, 0],
		    'options.issuerKey');
	}
	assert.object(opts.signatures, 'options.signatures');
	assert.buffer(opts.serial, 'options.serial');
	assert.date(opts.validFrom, 'options.validFrom');
	assert.date(opts.validUntil, 'optons.validUntil');
 
	assert.optionalArrayOfString(opts.purposes, 'options.purposes');
 
	this._hashCache = {};
 
	this.subjects = opts.subjects;
	this.issuer = opts.issuer;
	this.subjectKey = opts.subjectKey;
	this.issuerKey = opts.issuerKey;
	this.signatures = opts.signatures;
	this.serial = opts.serial;
	this.validFrom = opts.validFrom;
	this.validUntil = opts.validUntil;
	this.purposes = opts.purposes;
}
 
Certificate.formats = formats;
 
Certificate.prototype.toBuffer = function (format, options) {
	if (format === undefined)
		format = 'x509';
	assert.string(format, 'format');
	assert.object(formats[format], 'formats[format]');
	assert.optionalObject(options, 'options');
 
	return (formats[format].write(this, options));
};
 
Certificate.prototype.toString = function (format, options) {
	if (format === undefined)
		format = 'pem';
	return (this.toBuffer(format, options).toString());
};
 
Certificate.prototype.fingerprint = function (algo) {
	if (algo === undefined)
		algo = 'sha256';
	assert.string(algo, 'algorithm');
	var opts = {
		type: 'certificate',
		hash: this.hash(algo),
		algorithm: algo
	};
	return (new Fingerprint(opts));
};
 
Certificate.prototype.hash = function (algo) {
	assert.string(algo, 'algorithm');
	algo = algo.toLowerCase();
	if (algs.hashAlgs[algo] === undefined)
		throw (new InvalidAlgorithmError(algo));
 
	if (this._hashCache[algo])
		return (this._hashCache[algo]);
 
	var hash = crypto.createHash(algo).
	    update(this.toBuffer('x509')).digest();
	this._hashCache[algo] = hash;
	return (hash);
};
 
Certificate.prototype.isExpired = function (when) {
	if (when === undefined)
		when = new Date();
	return (!((when.getTime() >= this.validFrom.getTime()) &&
		(when.getTime() < this.validUntil.getTime())));
};
 
Certificate.prototype.isSignedBy = function (issuerCert) {
	utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer');
 
	if (!this.issuer.equals(issuerCert.subjects[0]))
		return (false);
	if (this.issuer.purposes && this.issuer.purposes.length > 0 &&
	    this.issuer.purposes.indexOf('ca') === -1) {
		return (false);
	}
 
	return (this.isSignedByKey(issuerCert.subjectKey));
};
 
Certificate.prototype.isSignedByKey = function (issuerKey) {
	utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey');
 
	if (this.issuerKey !== undefined) {
		return (this.issuerKey.
		    fingerprint('sha512').matches(issuerKey));
	}
 
	var fmt = Object.keys(this.signatures)[0];
	var valid = formats[fmt].verify(this, issuerKey);
	if (valid)
		this.issuerKey = issuerKey;
	return (valid);
};
 
Certificate.prototype.signWith = function (key) {
	utils.assertCompatible(key, PrivateKey, [1, 2], 'key');
	var fmts = Object.keys(formats);
	var didOne = false;
	for (var i = 0; i < fmts.length; ++i) {
		if (fmts[i] !== 'pem') {
			var ret = formats[fmts[i]].sign(this, key);
			if (ret === true)
				didOne = true;
		}
	}
	if (!didOne) {
		throw (new Error('Failed to sign the certificate for any ' +
		    'available certificate formats'));
	}
};
 
Certificate.createSelfSigned = function (subjectOrSubjects, key, options) {
	var subjects;
	if (Array.isArray(subjectOrSubjects))
		subjects = subjectOrSubjects;
	else
		subjects = [subjectOrSubjects];
 
	assert.arrayOfObject(subjects);
	subjects.forEach(function (subject) {
		utils.assertCompatible(subject, Identity, [1, 0], 'subject');
	});
 
	utils.assertCompatible(key, PrivateKey, [1, 2], 'private key');
 
	assert.optionalObject(options, 'options');
	if (options === undefined)
		options = {};
	assert.optionalObject(options.validFrom, 'options.validFrom');
	assert.optionalObject(options.validUntil, 'options.validUntil');
	var validFrom = options.validFrom;
	var validUntil = options.validUntil;
	if (validFrom === undefined)
		validFrom = new Date();
	if (validUntil === undefined) {
		assert.optionalNumber(options.lifetime, 'options.lifetime');
		var lifetime = options.lifetime;
		if (lifetime === undefined)
			lifetime = 10*365*24*3600;
		validUntil = new Date();
		validUntil.setTime(validUntil.getTime() + lifetime*1000);
	}
	assert.optionalBuffer(options.serial, 'options.serial');
	var serial = options.serial;
	if (serial === undefined)
		serial = new Buffer('0000000000000001', 'hex');
 
	var purposes = options.purposes;
	if (purposes === undefined)
		purposes = [];
 
	if (purposes.indexOf('signature') === -1)
		purposes.push('signature');
 
	/* Self-signed certs are always CAs. */
	if (purposes.indexOf('ca') === -1)
		purposes.push('ca');
	if (purposes.indexOf('crl') === -1)
		purposes.push('crl');
 
	/*
	 * If we weren't explicitly given any other purposes, do the sensible
	 * thing and add some basic ones depending on the subject type.
	 */
	if (purposes.length <= 3) {
		var hostSubjects = subjects.filter(function (subject) {
			return (subject.type === 'host');
		});
		var userSubjects = subjects.filter(function (subject) {
			return (subject.type === 'user');
		});
		if (hostSubjects.length > 0) {
			if (purposes.indexOf('serverAuth') === -1)
				purposes.push('serverAuth');
		}
		if (userSubjects.length > 0) {
			if (purposes.indexOf('clientAuth') === -1)
				purposes.push('clientAuth');
		}
		if (userSubjects.length > 0 || hostSubjects.length > 0) {
			if (purposes.indexOf('keyAgreement') === -1)
				purposes.push('keyAgreement');
			if (key.type === 'rsa' &&
			    purposes.indexOf('encryption') === -1)
				purposes.push('encryption');
		}
	}
 
	var cert = new Certificate({
		subjects: subjects,
		issuer: subjects[0],
		subjectKey: key.toPublic(),
		issuerKey: key.toPublic(),
		signatures: {},
		serial: serial,
		validFrom: validFrom,
		validUntil: validUntil,
		purposes: purposes
	});
	cert.signWith(key);
 
	return (cert);
};
 
Certificate.create =
    function (subjectOrSubjects, key, issuer, issuerKey, options) {
	var subjects;
	if (Array.isArray(subjectOrSubjects))
		subjects = subjectOrSubjects;
	else
		subjects = [subjectOrSubjects];
 
	assert.arrayOfObject(subjects);
	subjects.forEach(function (subject) {
		utils.assertCompatible(subject, Identity, [1, 0], 'subject');
	});
 
	utils.assertCompatible(key, Key, [1, 0], 'key');
	if (PrivateKey.isPrivateKey(key))
		key = key.toPublic();
	utils.assertCompatible(issuer, Identity, [1, 0], 'issuer');
	utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key');
 
	assert.optionalObject(options, 'options');
	if (options === undefined)
		options = {};
	assert.optionalObject(options.validFrom, 'options.validFrom');
	assert.optionalObject(options.validUntil, 'options.validUntil');
	var validFrom = options.validFrom;
	var validUntil = options.validUntil;
	if (validFrom === undefined)
		validFrom = new Date();
	if (validUntil === undefined) {
		assert.optionalNumber(options.lifetime, 'options.lifetime');
		var lifetime = options.lifetime;
		if (lifetime === undefined)
			lifetime = 10*365*24*3600;
		validUntil = new Date();
		validUntil.setTime(validUntil.getTime() + lifetime*1000);
	}
	assert.optionalBuffer(options.serial, 'options.serial');
	var serial = options.serial;
	if (serial === undefined)
		serial = new Buffer('0000000000000001', 'hex');
 
	var purposes = options.purposes;
	if (purposes === undefined)
		purposes = [];
 
	if (purposes.indexOf('signature') === -1)
		purposes.push('signature');
 
	if (options.ca === true) {
		if (purposes.indexOf('ca') === -1)
			purposes.push('ca');
		if (purposes.indexOf('crl') === -1)
			purposes.push('crl');
	}
 
	var hostSubjects = subjects.filter(function (subject) {
		return (subject.type === 'host');
	});
	var userSubjects = subjects.filter(function (subject) {
		return (subject.type === 'user');
	});
	if (hostSubjects.length > 0) {
		if (purposes.indexOf('serverAuth') === -1)
			purposes.push('serverAuth');
	}
	if (userSubjects.length > 0) {
		if (purposes.indexOf('clientAuth') === -1)
			purposes.push('clientAuth');
	}
	if (userSubjects.length > 0 || hostSubjects.length > 0) {
		if (purposes.indexOf('keyAgreement') === -1)
			purposes.push('keyAgreement');
		if (key.type === 'rsa' &&
		    purposes.indexOf('encryption') === -1)
			purposes.push('encryption');
	}
 
	var cert = new Certificate({
		subjects: subjects,
		issuer: issuer,
		subjectKey: key,
		issuerKey: issuerKey.toPublic(),
		signatures: {},
		serial: serial,
		validFrom: validFrom,
		validUntil: validUntil,
		purposes: purposes
	});
	cert.signWith(issuerKey);
 
	return (cert);
};
 
Certificate.parse = function (data, format, options) {
	if (typeof (data) !== 'string')
		assert.buffer(data, 'data');
	if (format === undefined)
		format = 'auto';
	assert.string(format, 'format');
	if (typeof (options) === 'string')
		options = { filename: options };
	assert.optionalObject(options, 'options');
	if (options === undefined)
		options = {};
	assert.optionalString(options.filename, 'options.filename');
	if (options.filename === undefined)
		options.filename = '(unnamed)';
 
	assert.object(formats[format], 'formats[format]');
 
	try {
		var k = formats[format].read(data, options);
		return (k);
	} catch (e) {
		throw (new CertificateParseError(options.filename, format, e));
	}
};
 
Certificate.isCertificate = function (obj, ver) {
	return (utils.isCompatible(obj, Certificate, ver));
};
 
/*
 * API versions for Certificate:
 * [1,0] -- initial ver
 */
Certificate.prototype._sshpkApiVersion = [1, 0];
 
Certificate._oldVersionDetect = function (obj) {
	return ([1, 0]);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/dhe.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/dhe.js

Statements: 14.36% (28 / 195)      Branches: 0% (0 / 76)      Functions: 0% (0 / 15)      Lines: 14.66% (28 / 191)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313    1   1 1 1 1 1   1 1   1   1   1                                                                                                                                             1           1           1   1                                                 1                                                 1   1                                                                       1                                                                                                                                                             1       1                                 1 1 1 1   1             1       1            
// Copyright 2015 Joyent, Inc.
 
module.exports = DiffieHellman;
 
var assert = require('assert-plus');
var crypto = require('crypto');
var algs = require('./algs');
var utils = require('./utils');
var ed;
 
var Key = require('./key');
var PrivateKey = require('./private-key');
 
var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined);
 
var ecdh, ec, jsbn;
 
function DiffieHellman(key) {
	utils.assertCompatible(key, Key, [1, 4], 'key');
	this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]);
	this._algo = key.type;
	this._curve = key.curve;
	this._key = key;
	if (key.type === 'dsa') {
		if (!CRYPTO_HAVE_ECDH) {
			throw (new Error('Due to bugs in the node 0.10 ' +
			    'crypto API, node 0.12.x or later is required ' +
			    'to use DH'));
		}
		this._dh = crypto.createDiffieHellman(
		    key.part.p.data, undefined,
		    key.part.g.data, undefined);
		this._p = key.part.p;
		this._g = key.part.g;
		if (this._isPriv)
			this._dh.setPrivateKey(key.part.x.data);
		this._dh.setPublicKey(key.part.y.data);
 
	} else if (key.type === 'ecdsa') {
		if (!CRYPTO_HAVE_ECDH) {
			if (ecdh === undefined)
				ecdh = require('ecc-jsbn');
			if (ec === undefined)
				ec = require('ecc-jsbn/lib/ec');
			if (jsbn === undefined)
				jsbn = require('jsbn').BigInteger;
 
			this._ecParams = new X9ECParameters(this._curve);
 
			if (this._isPriv) {
				this._priv = new ECPrivate(
				    this._ecParams, key.part.d.data);
			}
			return;
		}
 
		var curve = {
			'nistp256': 'prime256v1',
			'nistp384': 'secp384r1',
			'nistp521': 'secp521r1'
		}[key.curve];
		this._dh = crypto.createECDH(curve);
		if (typeof (this._dh) !== 'object' ||
		    typeof (this._dh.setPrivateKey) !== 'function') {
			CRYPTO_HAVE_ECDH = false;
			DiffieHellman.call(this, key);
			return;
		}
		if (this._isPriv)
			this._dh.setPrivateKey(key.part.d.data);
		this._dh.setPublicKey(key.part.Q.data);
 
	} else if (key.type === 'curve25519') {
		if (ed === undefined)
			ed = require('jodid25519');
 
		if (this._isPriv) {
			this._priv = key.part.r.data;
			if (this._priv[0] === 0x00)
				this._priv = this._priv.slice(1);
			this._priv = this._priv.slice(0, 32);
		}
 
	} else {
		throw (new Error('DH not supported for ' + key.type + ' keys'));
	}
}
 
DiffieHellman.prototype.getPublicKey = function () {
	if (this._isPriv)
		return (this._key.toPublic());
	return (this._key);
};
 
DiffieHellman.prototype.getPrivateKey = function () {
	if (this._isPriv)
		return (this._key);
	else
		return (undefined);
};
DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey;
 
DiffieHellman.prototype._keyCheck = function (pk, isPub) {
	assert.object(pk, 'key');
	if (!isPub)
		utils.assertCompatible(pk, PrivateKey, [1, 3], 'key');
	utils.assertCompatible(pk, Key, [1, 4], 'key');
 
	if (pk.type !== this._algo) {
		throw (new Error('A ' + pk.type + ' key cannot be used in ' +
		    this._algo + ' Diffie-Hellman'));
	}
 
	if (pk.curve !== this._curve) {
		throw (new Error('A key from the ' + pk.curve + ' curve ' +
		    'cannot be used with a ' + this._curve +
		    ' Diffie-Hellman'));
	}
 
	if (pk.type === 'dsa') {
		assert.deepEqual(pk.part.p, this._p,
		    'DSA key prime does not match');
		assert.deepEqual(pk.part.g, this._g,
		    'DSA key generator does not match');
	}
};
 
DiffieHellman.prototype.setKey = function (pk) {
	this._keyCheck(pk);
 
	if (pk.type === 'dsa') {
		this._dh.setPrivateKey(pk.part.x.data);
		this._dh.setPublicKey(pk.part.y.data);
 
	} else if (pk.type === 'ecdsa') {
		if (CRYPTO_HAVE_ECDH) {
			this._dh.setPrivateKey(pk.part.d.data);
			this._dh.setPublicKey(pk.part.Q.data);
		} else {
			this._priv = new ECPrivate(
			    this._ecParams, pk.part.d.data);
		}
 
	} else if (pk.type === 'curve25519') {
		this._priv = pk.part.r.data;
		if (this._priv[0] === 0x00)
			this._priv = this._priv.slice(1);
		this._priv = this._priv.slice(0, 32);
	}
	this._key = pk;
	this._isPriv = true;
};
DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey;
 
DiffieHellman.prototype.computeSecret = function (otherpk) {
	this._keyCheck(otherpk, true);
	if (!this._isPriv)
		throw (new Error('DH exchange has not been initialized with ' +
		    'a private key yet'));
 
	var pub;
	if (this._algo === 'dsa') {
		return (this._dh.computeSecret(
		    otherpk.part.y.data));
 
	} else if (this._algo === 'ecdsa') {
		if (CRYPTO_HAVE_ECDH) {
			return (this._dh.computeSecret(
			    otherpk.part.Q.data));
		} else {
			pub = new ECPublic(
			    this._ecParams, otherpk.part.Q.data);
			return (this._priv.deriveSharedSecret(pub));
		}
 
	} else if (this._algo === 'curve25519') {
		pub = otherpk.part.R.data;
		if (pub[0] === 0x00)
			pub = pub.slice(1);
 
		var secret = ed.dh.computeKey(
		    this._priv.toString('binary'),
		    pub.toString('binary'));
 
		return (new Buffer(secret, 'binary'));
	}
 
	throw (new Error('Invalid algorithm: ' + this._algo));
};
 
DiffieHellman.prototype.generateKey = function () {
	var parts = [];
	var priv, pub;
	if (this._algo === 'dsa') {
		this._dh.generateKeys();
 
		parts.push({name: 'p', data: this._p.data});
		parts.push({name: 'q', data: this._key.part.q.data});
		parts.push({name: 'g', data: this._g.data});
		parts.push({name: 'y', data: this._dh.getPublicKey()});
		parts.push({name: 'x', data: this._dh.getPrivateKey()});
		this._key = new PrivateKey({
			type: 'dsa',
			parts: parts
		});
		this._isPriv = true;
		return (this._key);
 
	} else if (this._algo === 'ecdsa') {
		if (CRYPTO_HAVE_ECDH) {
			this._dh.generateKeys();
 
			parts.push({name: 'curve',
			    data: new Buffer(this._curve)});
			parts.push({name: 'Q', data: this._dh.getPublicKey()});
			parts.push({name: 'd', data: this._dh.getPrivateKey()});
			this._key = new PrivateKey({
				type: 'ecdsa',
				curve: this._curve,
				parts: parts
			});
			this._isPriv = true;
			return (this._key);
 
		} else {
			var n = this._ecParams.getN();
			var r = new jsbn(crypto.randomBytes(n.bitLength()));
			var n1 = n.subtract(jsbn.ONE);
			priv = r.mod(n1).add(jsbn.ONE);
			pub = this._ecParams.getG().multiply(priv);
 
			priv = new Buffer(priv.toByteArray());
			pub = new Buffer(this._ecParams.getCurve().
			    encodePointHex(pub), 'hex');
 
			this._priv = new ECPrivate(this._ecParams, priv);
 
			parts.push({name: 'curve',
			    data: new Buffer(this._curve)});
			parts.push({name: 'Q', data: pub});
			parts.push({name: 'd', data: priv});
 
			this._key = new PrivateKey({
				type: 'ecdsa',
				curve: this._curve,
				parts: parts
			});
			this._isPriv = true;
			return (this._key);
		}
 
	} else if (this._algo === 'curve25519') {
		priv = ed.dh.generateKey();
		pub = ed.dh.publicKey(priv);
		this._priv = priv = new Buffer(priv, 'binary');
		pub = new Buffer(pub, 'binary');
 
		parts.push({name: 'R', data: pub});
		parts.push({name: 'r', data: Buffer.concat([priv, pub])});
		this._key = new PrivateKey({
			type: 'curve25519',
			parts: parts
		});
		this._isPriv = true;
		return (this._key);
	}
 
	throw (new Error('Invalid algorithm: ' + this._algo));
};
DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey;
 
/* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */
 
function X9ECParameters(name) {
	var params = algs.curves[name];
	assert.object(params);
 
	var p = new jsbn(params.p);
	var a = new jsbn(params.a);
	var b = new jsbn(params.b);
	var n = new jsbn(params.n);
	var h = jsbn.ONE;
	var curve = new ec.ECCurveFp(p, a, b);
	var G = curve.decodePointHex(params.G.toString('hex'));
 
	this.curve = curve;
	this.g = G;
	this.n = n;
	this.h = h;
}
X9ECParameters.prototype.getCurve = function () { return (this.curve); };
X9ECParameters.prototype.getG = function () { return (this.g); };
X9ECParameters.prototype.getN = function () { return (this.n); };
X9ECParameters.prototype.getH = function () { return (this.h); };
 
function ECPublic(params, buffer) {
	this._params = params;
	if (buffer[0] === 0x00)
		buffer = buffer.slice(1);
	this._pub = params.getCurve().decodePointHex(buffer.toString('hex'));
}
 
function ECPrivate(params, buffer) {
	this._params = params;
	this._priv = new jsbn(utils.mpNormalize(buffer));
}
ECPrivate.prototype.deriveSharedSecret = function (pubKey) {
	assert.ok(pubKey instanceof ECPublic);
	var S = pubKey._pub.multiply(this._priv);
	return (new Buffer(S.getX().toBigInteger().toByteArray()));
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/ed-compat.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/ed-compat.js

Statements: 28.57% (16 / 56)      Branches: 0% (0 / 20)      Functions: 0% (0 / 8)      Lines: 28.57% (16 / 56)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98    1         1 1 1 1 1   1                         1   1         1           1                                           1                         1   1         1           1                    
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	Verifier: Verifier,
	Signer: Signer
};
 
var nacl;
var stream = require('stream');
var util = require('util');
var assert = require('assert-plus');
var Signature = require('./signature');
 
function Verifier(key, hashAlgo) {
	if (nacl === undefined)
		nacl = require('tweetnacl');
 
	if (hashAlgo.toLowerCase() !== 'sha512')
		throw (new Error('ED25519 only supports the use of ' +
		    'SHA-512 hashes'));
 
	this.key = key;
	this.chunks = [];
 
	stream.Writable.call(this, {});
}
util.inherits(Verifier, stream.Writable);
 
Verifier.prototype._write = function (chunk, enc, cb) {
	this.chunks.push(chunk);
	cb();
};
 
Verifier.prototype.update = function (chunk) {
	if (typeof (chunk) === 'string')
		chunk = new Buffer(chunk, 'binary');
	this.chunks.push(chunk);
};
 
Verifier.prototype.verify = function (signature, fmt) {
	var sig;
	if (Signature.isSignature(signature, [2, 0])) {
		if (signature.type !== 'ed25519')
			return (false);
		sig = signature.toBuffer('raw');
 
	} else if (typeof (signature) === 'string') {
		sig = new Buffer(signature, 'base64');
 
	} else if (Signature.isSignature(signature, [1, 0])) {
		throw (new Error('signature was created by too old ' +
		    'a version of sshpk and cannot be verified'));
	}
 
	assert.buffer(sig);
	return (nacl.sign.detached.verify(
	    new Uint8Array(Buffer.concat(this.chunks)),
	    new Uint8Array(sig),
	    new Uint8Array(this.key.part.R.data)));
};
 
function Signer(key, hashAlgo) {
	if (nacl === undefined)
		nacl = require('tweetnacl');
 
	if (hashAlgo.toLowerCase() !== 'sha512')
		throw (new Error('ED25519 only supports the use of ' +
		    'SHA-512 hashes'));
 
	this.key = key;
	this.chunks = [];
 
	stream.Writable.call(this, {});
}
util.inherits(Signer, stream.Writable);
 
Signer.prototype._write = function (chunk, enc, cb) {
	this.chunks.push(chunk);
	cb();
};
 
Signer.prototype.update = function (chunk) {
	if (typeof (chunk) === 'string')
		chunk = new Buffer(chunk, 'binary');
	this.chunks.push(chunk);
};
 
Signer.prototype.sign = function () {
	var sig = nacl.sign.detached(
	    new Uint8Array(Buffer.concat(this.chunks)),
	    new Uint8Array(this.key.part.r.data));
	var sigBuf = new Buffer(sig);
	var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw');
	sigObj.hashAlgorithm = 'sha512';
	return (sigObj);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/errors.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/errors.js

Statements: 26.32% (15 / 57)      Branches: 0% (0 / 16)      Functions: 0% (0 / 6)      Lines: 26.32% (15 / 57)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86    1 1   1                       1   1             1   1                   1   1                   1   1                   1   1                   1   1                  
// Copyright 2015 Joyent, Inc.
 
var assert = require('assert-plus');
var util = require('util');
 
function FingerprintFormatError(fp, format) {
	if (Error.captureStackTrace)
		Error.captureStackTrace(this, FingerprintFormatError);
	this.name = 'FingerprintFormatError';
	this.fingerprint = fp;
	this.format = format;
	this.message = 'Fingerprint format is not supported, or is invalid: ';
	if (fp !== undefined)
		this.message += ' fingerprint = ' + fp;
	if (format !== undefined)
		this.message += ' format = ' + format;
}
util.inherits(FingerprintFormatError, Error);
 
function InvalidAlgorithmError(alg) {
	if (Error.captureStackTrace)
		Error.captureStackTrace(this, InvalidAlgorithmError);
	this.name = 'InvalidAlgorithmError';
	this.algorithm = alg;
	this.message = 'Algorithm "' + alg + '" is not supported';
}
util.inherits(InvalidAlgorithmError, Error);
 
function KeyParseError(name, format, innerErr) {
	if (Error.captureStackTrace)
		Error.captureStackTrace(this, KeyParseError);
	this.name = 'KeyParseError';
	this.format = format;
	this.keyName = name;
	this.innerErr = innerErr;
	this.message = 'Failed to parse ' + name + ' as a valid ' + format +
	    ' format key: ' + innerErr.message;
}
util.inherits(KeyParseError, Error);
 
function SignatureParseError(type, format, innerErr) {
	if (Error.captureStackTrace)
		Error.captureStackTrace(this, SignatureParseError);
	this.name = 'SignatureParseError';
	this.type = type;
	this.format = format;
	this.innerErr = innerErr;
	this.message = 'Failed to parse the given data as a ' + type +
	    ' signature in ' + format + ' format: ' + innerErr.message;
}
util.inherits(SignatureParseError, Error);
 
function CertificateParseError(name, format, innerErr) {
	if (Error.captureStackTrace)
		Error.captureStackTrace(this, CertificateParseError);
	this.name = 'CertificateParseError';
	this.format = format;
	this.certName = name;
	this.innerErr = innerErr;
	this.message = 'Failed to parse ' + name + ' as a valid ' + format +
	    ' format certificate: ' + innerErr.message;
}
util.inherits(CertificateParseError, Error);
 
function KeyEncryptedError(name, format) {
	if (Error.captureStackTrace)
		Error.captureStackTrace(this, KeyEncryptedError);
	this.name = 'KeyEncryptedError';
	this.format = format;
	this.keyName = name;
	this.message = 'The ' + format + ' format key ' + name + ' is ' +
	    'encrypted (password-protected), and no passphrase was ' +
	    'provided in `options`';
}
util.inherits(KeyEncryptedError, Error);
 
module.exports = {
	FingerprintFormatError: FingerprintFormatError,
	InvalidAlgorithmError: InvalidAlgorithmError,
	KeyParseError: KeyParseError,
	SignatureParseError: SignatureParseError,
	KeyEncryptedError: KeyEncryptedError,
	CertificateParseError: CertificateParseError
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/fingerprint.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/fingerprint.js

Statements: 21.05% (20 / 95)      Branches: 0% (0 / 39)      Functions: 0% (0 / 10)      Lines: 21.28% (20 / 94)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163    1   1 1 1 1 1 1 1   1 1   1                           1                                       1                                       1                                                                                                                           1         1         1       1                 1   1            
// Copyright 2015 Joyent, Inc.
 
module.exports = Fingerprint;
 
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var errs = require('./errors');
var Key = require('./key');
var Certificate = require('./certificate');
var utils = require('./utils');
 
var FingerprintFormatError = errs.FingerprintFormatError;
var InvalidAlgorithmError = errs.InvalidAlgorithmError;
 
function Fingerprint(opts) {
	assert.object(opts, 'options');
	assert.string(opts.type, 'options.type');
	assert.buffer(opts.hash, 'options.hash');
	assert.string(opts.algorithm, 'options.algorithm');
 
	this.algorithm = opts.algorithm.toLowerCase();
	if (algs.hashAlgs[this.algorithm] !== true)
		throw (new InvalidAlgorithmError(this.algorithm));
 
	this.hash = opts.hash;
	this.type = opts.type;
}
 
Fingerprint.prototype.toString = function (format) {
	if (format === undefined) {
		if (this.algorithm === 'md5')
			format = 'hex';
		else
			format = 'base64';
	}
	assert.string(format);
 
	switch (format) {
	case 'hex':
		return (addColons(this.hash.toString('hex')));
	case 'base64':
		return (sshBase64Format(this.algorithm,
		    this.hash.toString('base64')));
	default:
		throw (new FingerprintFormatError(undefined, format));
	}
};
 
Fingerprint.prototype.matches = function (other) {
	assert.object(other, 'key or certificate');
	if (this.type === 'key') {
		utils.assertCompatible(other, Key, [1, 0], 'key');
	} else {
		utils.assertCompatible(other, Certificate, [1, 0],
		    'certificate');
	}
 
	var theirHash = other.hash(this.algorithm);
	var theirHash2 = crypto.createHash(this.algorithm).
	    update(theirHash).digest('base64');
 
	if (this.hash2 === undefined)
		this.hash2 = crypto.createHash(this.algorithm).
		    update(this.hash).digest('base64');
 
	return (this.hash2 === theirHash2);
};
 
Fingerprint.parse = function (fp, options) {
	assert.string(fp, 'fingerprint');
 
	var alg, hash, enAlgs;
	if (Array.isArray(options)) {
		enAlgs = options;
		options = {};
	}
	assert.optionalObject(options, 'options');
	if (options === undefined)
		options = {};
	if (options.enAlgs !== undefined)
		enAlgs = options.enAlgs;
	assert.optionalArrayOfString(enAlgs, 'algorithms');
 
	var parts = fp.split(':');
	if (parts.length == 2) {
		alg = parts[0].toLowerCase();
		/*JSSTYLED*/
		var base64RE = /^[A-Za-z0-9+\/=]+$/;
		if (!base64RE.test(parts[1]))
			throw (new FingerprintFormatError(fp));
		try {
			hash = new Buffer(parts[1], 'base64');
		} catch (e) {
			throw (new FingerprintFormatError(fp));
		}
	} else if (parts.length > 2) {
		alg = 'md5';
		if (parts[0].toLowerCase() === 'md5')
			parts = parts.slice(1);
		parts = parts.join('');
		/*JSSTYLED*/
		var md5RE = /^[a-fA-F0-9]+$/;
		if (!md5RE.test(parts))
			throw (new FingerprintFormatError(fp));
		try {
			hash = new Buffer(parts, 'hex');
		} catch (e) {
			throw (new FingerprintFormatError(fp));
		}
	}
 
	if (alg === undefined)
		throw (new FingerprintFormatError(fp));
 
	if (algs.hashAlgs[alg] === undefined)
		throw (new InvalidAlgorithmError(alg));
 
	if (enAlgs !== undefined) {
		enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); });
		if (enAlgs.indexOf(alg) === -1)
			throw (new InvalidAlgorithmError(alg));
	}
 
	return (new Fingerprint({
		algorithm: alg,
		hash: hash,
		type: options.type || 'key'
	}));
};
 
function addColons(s) {
	/*JSSTYLED*/
	return (s.replace(/(.{2})(?=.)/g, '$1:'));
}
 
function base64Strip(s) {
	/*JSSTYLED*/
	return (s.replace(/=*$/, ''));
}
 
function sshBase64Format(alg, h) {
	return (alg.toUpperCase() + ':' + base64Strip(h));
}
 
Fingerprint.isFingerprint = function (obj, ver) {
	return (utils.isCompatible(obj, Fingerprint, ver));
};
 
/*
 * API versions for Fingerprint:
 * [1,0] -- initial ver
 * [1,1] -- first tagged ver
 */
Fingerprint.prototype._sshpkApiVersion = [1, 1];
 
Fingerprint._oldVersionDetect = function (obj) {
	assert.func(obj.toString);
	assert.func(obj.matches);
	return ([1, 0]);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/identity.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/identity.js

Statements: 23.95% (40 / 167)      Branches: 0% (0 / 85)      Functions: 5.56% (1 / 18)      Lines: 23.95% (40 / 167)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279    1   1 1 1 1 1 1 1 1 1     1   1 1 1 1 1 1 1 1 1 1 1   1 1 10     1                                                                                                                                                           1                         1   1   1                                               1                               1                               1                 1                 1                 1                         1                                                                             1               1   1        
// Copyright 2016 Joyent, Inc.
 
module.exports = Identity;
 
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors');
var util = require('util');
var utils = require('./utils');
var asn1 = require('asn1');
 
/*JSSTYLED*/
var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i;
 
var oids = {};
oids.cn = '2.5.4.3';
oids.o = '2.5.4.10';
oids.ou = '2.5.4.11';
oids.l = '2.5.4.7';
oids.s = '2.5.4.8';
oids.c = '2.5.4.6';
oids.sn = '2.5.4.4';
oids.dc = '0.9.2342.19200300.100.1.25';
oids.uid = '0.9.2342.19200300.100.1.1';
oids.mail = '0.9.2342.19200300.100.1.3';
 
var unoids = {};
Object.keys(oids).forEach(function (k) {
	unoids[oids[k]] = k;
});
 
function Identity(opts) {
	var self = this;
	assert.object(opts, 'options');
	assert.arrayOfObject(opts.components, 'options.components');
	this.components = opts.components;
	this.componentLookup = {};
	this.components.forEach(function (c) {
		if (c.name && !c.oid)
			c.oid = oids[c.name];
		if (c.oid && !c.name)
			c.name = unoids[c.oid];
		if (self.componentLookup[c.name] === undefined)
			self.componentLookup[c.name] = [];
		self.componentLookup[c.name].push(c);
	});
	if (this.componentLookup.cn && this.componentLookup.cn.length > 0) {
		this.cn = this.componentLookup.cn[0].value;
	}
	assert.optionalString(opts.type, 'options.type');
	if (opts.type === undefined) {
		if (this.components.length === 1 &&
		    this.componentLookup.cn &&
		    this.componentLookup.cn.length === 1 &&
		    this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
			this.type = 'host';
			this.hostname = this.componentLookup.cn[0].value;
 
		} else if (this.componentLookup.dc &&
		    this.components.length === this.componentLookup.dc.length) {
			this.type = 'host';
			this.hostname = this.componentLookup.dc.map(
			    function (c) {
				return (c.value);
			}).join('.');
 
		} else if (this.componentLookup.uid &&
		    this.components.length ===
		    this.componentLookup.uid.length) {
			this.type = 'user';
			this.uid = this.componentLookup.uid[0].value;
 
		} else if (this.componentLookup.cn &&
		    this.componentLookup.cn.length === 1 &&
		    this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
			this.type = 'host';
			this.hostname = this.componentLookup.cn[0].value;
 
		} else if (this.componentLookup.uid &&
		    this.componentLookup.uid.length === 1) {
			this.type = 'user';
			this.uid = this.componentLookup.uid[0].value;
 
		} else if (this.componentLookup.mail &&
		    this.componentLookup.mail.length === 1) {
			this.type = 'email';
			this.email = this.componentLookup.mail[0].value;
 
		} else if (this.componentLookup.cn &&
		    this.componentLookup.cn.length === 1) {
			this.type = 'user';
			this.uid = this.componentLookup.cn[0].value;
 
		} else {
			this.type = 'unknown';
		}
	} else {
		this.type = opts.type;
		if (this.type === 'host')
			this.hostname = opts.hostname;
		else if (this.type === 'user')
			this.uid = opts.uid;
		else if (this.type === 'email')
			this.email = opts.email;
		else
			throw (new Error('Unknown type ' + this.type));
	}
}
 
Identity.prototype.toString = function () {
	return (this.components.map(function (c) {
		return (c.name.toUpperCase() + '=' + c.value);
	}).join(', '));
};
 
/*
 * These are from X.680 -- PrintableString allowed chars are in section 37.4
 * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to
 * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006
 * (the basic ASCII character set).
 */
/* JSSTYLED */
var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/;
/* JSSTYLED */
var NOT_IA5 = /[^\x00-\x7f]/;
 
Identity.prototype.toAsn1 = function (der, tag) {
	der.startSequence(tag);
	this.components.forEach(function (c) {
		der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set);
		der.startSequence();
		der.writeOID(c.oid);
		/*
		 * If we fit in a PrintableString, use that. Otherwise use an
		 * IA5String or UTF8String.
		 */
		if (c.value.match(NOT_IA5)) {
			var v = new Buffer(c.value, 'utf8');
			der.writeBuffer(v, asn1.Ber.Utf8String);
		} else if (c.value.match(NOT_PRINTABLE)) {
			der.writeString(c.value, asn1.Ber.IA5String);
		} else {
			der.writeString(c.value, asn1.Ber.PrintableString);
		}
		der.endSequence();
		der.endSequence();
	});
	der.endSequence();
};
 
function globMatch(a, b) {
	if (a === '**' || b === '**')
		return (true);
	var aParts = a.split('.');
	var bParts = b.split('.');
	if (aParts.length !== bParts.length)
		return (false);
	for (var i = 0; i < aParts.length; ++i) {
		if (aParts[i] === '*' || bParts[i] === '*')
			continue;
		if (aParts[i] !== bParts[i])
			return (false);
	}
	return (true);
}
 
Identity.prototype.equals = function (other) {
	if (!Identity.isIdentity(other, [1, 0]))
		return (false);
	if (other.components.length !== this.components.length)
		return (false);
	for (var i = 0; i < this.components.length; ++i) {
		if (this.components[i].oid !== other.components[i].oid)
			return (false);
		if (!globMatch(this.components[i].value,
		    other.components[i].value)) {
			return (false);
		}
	}
	return (true);
};
 
Identity.forHost = function (hostname) {
	assert.string(hostname, 'hostname');
	return (new Identity({
		type: 'host',
		hostname: hostname,
		components: [ { name: 'cn', value: hostname } ]
	}));
};
 
Identity.forUser = function (uid) {
	assert.string(uid, 'uid');
	return (new Identity({
		type: 'user',
		uid: uid,
		components: [ { name: 'uid', value: uid } ]
	}));
};
 
Identity.forEmail = function (email) {
	assert.string(email, 'email');
	return (new Identity({
		type: 'email',
		email: email,
		components: [ { name: 'mail', value: email } ]
	}));
};
 
Identity.parseDN = function (dn) {
	assert.string(dn, 'dn');
	var parts = dn.split(',');
	var cmps = parts.map(function (c) {
		c = c.trim();
		var eqPos = c.indexOf('=');
		var name = c.slice(0, eqPos).toLowerCase();
		var value = c.slice(eqPos + 1);
		return ({ name: name, value: value });
	});
	return (new Identity({ components: cmps }));
};
 
Identity.parseAsn1 = function (der, top) {
	var components = [];
	der.readSequence(top);
	var end = der.offset + der.length;
	while (der.offset < end) {
		der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set);
		var after = der.offset + der.length;
		der.readSequence();
		var oid = der.readOID();
		var type = der.peek();
		var value;
		switch (type) {
		case asn1.Ber.PrintableString:
		case asn1.Ber.IA5String:
		case asn1.Ber.OctetString:
		case asn1.Ber.T61String:
			value = der.readString(type);
			break;
		case asn1.Ber.Utf8String:
			value = der.readString(type, true);
			value = value.toString('utf8');
			break;
		case asn1.Ber.CharacterString:
		case asn1.Ber.BMPString:
			value = der.readString(type, true);
			value = value.toString('utf16le');
			break;
		default:
			throw (new Error('Unknown asn1 type ' + type));
		}
		components.push({ oid: oid, value: value });
		der._offset = after;
	}
	der._offset = end;
	return (new Identity({
		components: components
	}));
};
 
Identity.isIdentity = function (obj, ver) {
	return (utils.isCompatible(obj, Identity, ver));
};
 
/*
 * API versions for Identity:
 * [1,0] -- initial ver
 */
Identity.prototype._sshpkApiVersion = [1, 0];
 
Identity._oldVersionDetect = function (obj) {
	return ([1, 0]);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/index.js

Statements: 100% (8 / 8)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (8 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40    1 1 1 1 1 1 1   1                                                          
// Copyright 2015 Joyent, Inc.
 
var Key = require('./key');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var PrivateKey = require('./private-key');
var Certificate = require('./certificate');
var Identity = require('./identity');
var errs = require('./errors');
 
module.exports = {
	/* top-level classes */
	Key: Key,
	parseKey: Key.parse,
	Fingerprint: Fingerprint,
	parseFingerprint: Fingerprint.parse,
	Signature: Signature,
	parseSignature: Signature.parse,
	PrivateKey: PrivateKey,
	parsePrivateKey: PrivateKey.parse,
	Certificate: Certificate,
	parseCertificate: Certificate.parse,
	createSelfSignedCertificate: Certificate.createSelfSigned,
	createCertificate: Certificate.create,
	Identity: Identity,
	identityFromDN: Identity.parseDN,
	identityForHost: Identity.forHost,
	identityForUser: Identity.forUser,
	identityForEmail: Identity.forEmail,
 
	/* errors */
	FingerprintFormatError: errs.FingerprintFormatError,
	InvalidAlgorithmError: errs.InvalidAlgorithmError,
	KeyParseError: errs.KeyParseError,
	SignatureParseError: errs.SignatureParseError,
	KeyEncryptedError: errs.KeyEncryptedError,
	CertificateParseError: errs.CertificateParseError
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/key.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/key.js

Statements: 21.11% (38 / 180)      Branches: 0% (0 / 85)      Functions: 0% (0 / 12)      Lines: 21.11% (38 / 180)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272    1   1 1 1 1 1 1 1 1 1 1   1 1         1 1   1 1 1 1 1 1 1 1 1   1                                                                                     1   1                               1       1                             1                       1                                     1                                                                                                                   1           1   1                                                             1                         1   1                            
// Copyright 2015 Joyent, Inc.
 
module.exports = Key;
 
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var DiffieHellman = require('./dhe');
var errs = require('./errors');
var utils = require('./utils');
var PrivateKey = require('./private-key');
var edCompat;
 
try {
	edCompat = require('./ed-compat');
} catch (e) {
	/* Just continue through, and bail out if we try to use it. */
}
 
var InvalidAlgorithmError = errs.InvalidAlgorithmError;
var KeyParseError = errs.KeyParseError;
 
var formats = {};
formats['auto'] = require('./formats/auto');
formats['pem'] = require('./formats/pem');
formats['pkcs1'] = require('./formats/pkcs1');
formats['pkcs8'] = require('./formats/pkcs8');
formats['rfc4253'] = require('./formats/rfc4253');
formats['ssh'] = require('./formats/ssh');
formats['ssh-private'] = require('./formats/ssh-private');
formats['openssh'] = formats['ssh-private'];
 
function Key(opts) {
	assert.object(opts, 'options');
	assert.arrayOfObject(opts.parts, 'options.parts');
	assert.string(opts.type, 'options.type');
	assert.optionalString(opts.comment, 'options.comment');
 
	var algInfo = algs.info[opts.type];
	if (typeof (algInfo) !== 'object')
		throw (new InvalidAlgorithmError(opts.type));
 
	var partLookup = {};
	for (var i = 0; i < opts.parts.length; ++i) {
		var part = opts.parts[i];
		partLookup[part.name] = part;
	}
 
	this.type = opts.type;
	this.parts = opts.parts;
	this.part = partLookup;
	this.comment = undefined;
	this.source = opts.source;
 
	/* for speeding up hashing/fingerprint operations */
	this._rfc4253Cache = opts._rfc4253Cache;
	this._hashCache = {};
 
	var sz;
	this.curve = undefined;
	if (this.type === 'ecdsa') {
		var curve = this.part.curve.data.toString();
		this.curve = curve;
		sz = algs.curves[curve].size;
	} else if (this.type === 'ed25519') {
		sz = 256;
		this.curve = 'curve25519';
	} else {
		var szPart = this.part[algInfo.sizePart];
		sz = szPart.data.length;
		sz = sz * 8 - utils.countZeros(szPart.data);
	}
	this.size = sz;
}
 
Key.formats = formats;
 
Key.prototype.toBuffer = function (format, options) {
	if (format === undefined)
		format = 'ssh';
	assert.string(format, 'format');
	assert.object(formats[format], 'formats[format]');
	assert.optionalObject(options, 'options');
 
	if (format === 'rfc4253') {
		if (this._rfc4253Cache === undefined)
			this._rfc4253Cache = formats['rfc4253'].write(this);
		return (this._rfc4253Cache);
	}
 
	return (formats[format].write(this, options));
};
 
Key.prototype.toString = function (format, options) {
	return (this.toBuffer(format, options).toString());
};
 
Key.prototype.hash = function (algo) {
	assert.string(algo, 'algorithm');
	algo = algo.toLowerCase();
	if (algs.hashAlgs[algo] === undefined)
		throw (new InvalidAlgorithmError(algo));
 
	if (this._hashCache[algo])
		return (this._hashCache[algo]);
 
	var hash = crypto.createHash(algo).
	    update(this.toBuffer('rfc4253')).digest();
	this._hashCache[algo] = hash;
	return (hash);
};
 
Key.prototype.fingerprint = function (algo) {
	if (algo === undefined)
		algo = 'sha256';
	assert.string(algo, 'algorithm');
	var opts = {
		type: 'key',
		hash: this.hash(algo),
		algorithm: algo
	};
	return (new Fingerprint(opts));
};
 
Key.prototype.defaultHashAlgorithm = function () {
	var hashAlgo = 'sha1';
	if (this.type === 'rsa')
		hashAlgo = 'sha256';
	if (this.type === 'dsa' && this.size > 1024)
		hashAlgo = 'sha256';
	if (this.type === 'ed25519')
		hashAlgo = 'sha512';
	if (this.type === 'ecdsa') {
		if (this.size <= 256)
			hashAlgo = 'sha256';
		else if (this.size <= 384)
			hashAlgo = 'sha384';
		else
			hashAlgo = 'sha512';
	}
	return (hashAlgo);
};
 
Key.prototype.createVerify = function (hashAlgo) {
	if (hashAlgo === undefined)
		hashAlgo = this.defaultHashAlgorithm();
	assert.string(hashAlgo, 'hash algorithm');
 
	/* ED25519 is not supported by OpenSSL, use a javascript impl. */
	if (this.type === 'ed25519' && edCompat !== undefined)
		return (new edCompat.Verifier(this, hashAlgo));
	if (this.type === 'curve25519')
		throw (new Error('Curve25519 keys are not suitable for ' +
		    'signing or verification'));
 
	var v, nm, err;
	try {
		nm = hashAlgo.toUpperCase();
		v = crypto.createVerify(nm);
	} catch (e) {
		err = e;
	}
	if (v === undefined || (err instanceof Error &&
	    err.message.match(/Unknown message digest/))) {
		nm = 'RSA-';
		nm += hashAlgo.toUpperCase();
		v = crypto.createVerify(nm);
	}
	assert.ok(v, 'failed to create verifier');
	var oldVerify = v.verify.bind(v);
	var key = this.toBuffer('pkcs8');
	var self = this;
	v.verify = function (signature, fmt) {
		if (Signature.isSignature(signature, [2, 0])) {
			if (signature.type !== self.type)
				return (false);
			if (signature.hashAlgorithm &&
			    signature.hashAlgorithm !== hashAlgo)
				return (false);
			return (oldVerify(key, signature.toBuffer('asn1')));
 
		} else if (typeof (signature) === 'string' ||
		    Buffer.isBuffer(signature)) {
			return (oldVerify(key, signature, fmt));
 
		/*
		 * Avoid doing this on valid arguments, walking the prototype
		 * chain can be quite slow.
		 */
		} else if (Signature.isSignature(signature, [1, 0])) {
			throw (new Error('signature was created by too old ' +
			    'a version of sshpk and cannot be verified'));
 
		} else {
			throw (new TypeError('signature must be a string, ' +
			    'Buffer, or Signature object'));
		}
	};
	return (v);
};
 
Key.prototype.createDiffieHellman = function () {
	if (this.type === 'rsa')
		throw (new Error('RSA keys do not support Diffie-Hellman'));
 
	return (new DiffieHellman(this));
};
Key.prototype.createDH = Key.prototype.createDiffieHellman;
 
Key.parse = function (data, format, options) {
	if (typeof (data) !== 'string')
		assert.buffer(data, 'data');
	if (format === undefined)
		format = 'auto';
	assert.string(format, 'format');
	if (typeof (options) === 'string')
		options = { filename: options };
	assert.optionalObject(options, 'options');
	if (options === undefined)
		options = {};
	assert.optionalString(options.filename, 'options.filename');
	if (options.filename === undefined)
		options.filename = '(unnamed)';
 
	assert.object(formats[format], 'formats[format]');
 
	try {
		var k = formats[format].read(data, options);
		if (k instanceof PrivateKey)
			k = k.toPublic();
		if (!k.comment)
			k.comment = options.filename;
		return (k);
	} catch (e) {
		if (e.name === 'KeyEncryptedError')
			throw (e);
		throw (new KeyParseError(options.filename, format, e));
	}
};
 
Key.isKey = function (obj, ver) {
	return (utils.isCompatible(obj, Key, ver));
};
 
/*
 * API versions for Key:
 * [1,0] -- initial ver, may take Signature for createVerify or may not
 * [1,1] -- added pkcs1, pkcs8 formats
 * [1,2] -- added auto, ssh-private, openssh formats
 * [1,3] -- added defaultHashAlgorithm
 * [1,4] -- added ed support, createDH
 * [1,5] -- first explicitly tagged version
 */
Key.prototype._sshpkApiVersion = [1, 5];
 
Key._oldVersionDetect = function (obj) {
	assert.func(obj.toBuffer);
	assert.func(obj.fingerprint);
	if (obj.createDH)
		return ([1, 4]);
	if (obj.defaultHashAlgorithm)
		return ([1, 3]);
	if (obj.formats['auto'])
		return ([1, 2]);
	if (obj.formats['pkcs1'])
		return ([1, 1]);
	return ([1, 0]);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/private-key.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/private-key.js

Statements: 26.53% (39 / 147)      Branches: 0% (0 / 57)      Functions: 0% (0 / 11)      Lines: 26.53% (39 / 147)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233    1   1 1 1 1 1 1 1 1 1 1   1 1         1   1 1 1   1 1 1 1 1 1 1 1 1   1           1   1   1                   1       1                                         1                                                                                                   1       1                                                                               1                                                           1                       1   1                        
// Copyright 2015 Joyent, Inc.
 
module.exports = PrivateKey;
 
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors');
var util = require('util');
var utils = require('./utils');
var edCompat;
var ed;
 
try {
	edCompat = require('./ed-compat');
} catch (e) {
	/* Just continue through, and bail out if we try to use it. */
}
 
var Key = require('./key');
 
var InvalidAlgorithmError = errs.InvalidAlgorithmError;
var KeyParseError = errs.KeyParseError;
var KeyEncryptedError = errs.KeyEncryptedError;
 
var formats = {};
formats['auto'] = require('./formats/auto');
formats['pem'] = require('./formats/pem');
formats['pkcs1'] = require('./formats/pkcs1');
formats['pkcs8'] = require('./formats/pkcs8');
formats['rfc4253'] = require('./formats/rfc4253');
formats['ssh-private'] = require('./formats/ssh-private');
formats['openssh'] = formats['ssh-private'];
formats['ssh'] = formats['ssh-private'];
 
function PrivateKey(opts) {
	assert.object(opts, 'options');
	Key.call(this, opts);
 
	this._pubCache = undefined;
}
util.inherits(PrivateKey, Key);
 
PrivateKey.formats = formats;
 
PrivateKey.prototype.toBuffer = function (format, options) {
	if (format === undefined)
		format = 'pkcs1';
	assert.string(format, 'format');
	assert.object(formats[format], 'formats[format]');
	assert.optionalObject(options, 'options');
 
	return (formats[format].write(this, options));
};
 
PrivateKey.prototype.hash = function (algo) {
	return (this.toPublic().hash(algo));
};
 
PrivateKey.prototype.toPublic = function () {
	if (this._pubCache)
		return (this._pubCache);
 
	var algInfo = algs.info[this.type];
	var pubParts = [];
	for (var i = 0; i < algInfo.parts.length; ++i) {
		var p = algInfo.parts[i];
		pubParts.push(this.part[p]);
	}
 
	this._pubCache = new Key({
		type: this.type,
		source: this,
		parts: pubParts
	});
	if (this.comment)
		this._pubCache.comment = this.comment;
	return (this._pubCache);
};
 
PrivateKey.prototype.derive = function (newType, newSize) {
	assert.string(newType, 'type');
	assert.optionalNumber(newSize, 'size');
	var priv, pub;
 
	if (this.type === 'ed25519' && newType === 'curve25519') {
		if (ed === undefined)
			ed = require('jodid25519');
 
		priv = this.part.r.data;
		if (priv[0] === 0x00)
			priv = priv.slice(1);
		priv = priv.slice(0, 32);
 
		pub = ed.dh.publicKey(priv);
		priv = utils.mpNormalize(Buffer.concat([priv, pub]));
 
		return (new PrivateKey({
			type: 'curve25519',
			parts: [
				{ name: 'R', data: utils.mpNormalize(pub) },
				{ name: 'r', data: priv }
			]
		}));
	} else if (this.type === 'curve25519' && newType === 'ed25519') {
		if (ed === undefined)
			ed = require('jodid25519');
 
		priv = this.part.r.data;
		if (priv[0] === 0x00)
			priv = priv.slice(1);
		priv = priv.slice(0, 32);
 
		pub = ed.eddsa.publicKey(priv.toString('binary'));
		pub = new Buffer(pub, 'binary');
 
		priv = utils.mpNormalize(Buffer.concat([priv, pub]));
 
		return (new PrivateKey({
			type: 'ed25519',
			parts: [
				{ name: 'R', data: utils.mpNormalize(pub) },
				{ name: 'r', data: priv }
			]
		}));
	}
	throw (new Error('Key derivation not supported from ' + this.type +
	    ' to ' + newType));
};
 
PrivateKey.prototype.createVerify = function (hashAlgo) {
	return (this.toPublic().createVerify(hashAlgo));
};
 
PrivateKey.prototype.createSign = function (hashAlgo) {
	if (hashAlgo === undefined)
		hashAlgo = this.defaultHashAlgorithm();
	assert.string(hashAlgo, 'hash algorithm');
 
	/* ED25519 is not supported by OpenSSL, use a javascript impl. */
	if (this.type === 'ed25519' && edCompat !== undefined)
		return (new edCompat.Signer(this, hashAlgo));
	if (this.type === 'curve25519')
		throw (new Error('Curve25519 keys are not suitable for ' +
		    'signing or verification'));
 
	var v, nm, err;
	try {
		nm = hashAlgo.toUpperCase();
		v = crypto.createSign(nm);
	} catch (e) {
		err = e;
	}
	if (v === undefined || (err instanceof Error &&
	    err.message.match(/Unknown message digest/))) {
		nm = 'RSA-';
		nm += hashAlgo.toUpperCase();
		v = crypto.createSign(nm);
	}
	assert.ok(v, 'failed to create verifier');
	var oldSign = v.sign.bind(v);
	var key = this.toBuffer('pkcs1');
	var type = this.type;
	v.sign = function () {
		var sig = oldSign(key);
		if (typeof (sig) === 'string')
			sig = new Buffer(sig, 'binary');
		sig = Signature.parse(sig, type, 'asn1');
		sig.hashAlgorithm = hashAlgo;
		return (sig);
	};
	return (v);
};
 
PrivateKey.parse = function (data, format, options) {
	if (typeof (data) !== 'string')
		assert.buffer(data, 'data');
	if (format === undefined)
		format = 'auto';
	assert.string(format, 'format');
	if (typeof (options) === 'string')
		options = { filename: options };
	assert.optionalObject(options, 'options');
	if (options === undefined)
		options = {};
	assert.optionalString(options.filename, 'options.filename');
	if (options.filename === undefined)
		options.filename = '(unnamed)';
 
	assert.object(formats[format], 'formats[format]');
 
	try {
		var k = formats[format].read(data, options);
		assert.ok(k instanceof PrivateKey, 'key is not a private key');
		if (!k.comment)
			k.comment = options.filename;
		return (k);
	} catch (e) {
		if (e.name === 'KeyEncryptedError')
			throw (e);
		throw (new KeyParseError(options.filename, format, e));
	}
};
 
PrivateKey.isPrivateKey = function (obj, ver) {
	return (utils.isCompatible(obj, PrivateKey, ver));
};
 
/*
 * API versions for PrivateKey:
 * [1,0] -- initial ver
 * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats
 * [1,2] -- added defaultHashAlgorithm
 * [1,3] -- added derive, ed, createDH
 * [1,4] -- first tagged version
 */
PrivateKey.prototype._sshpkApiVersion = [1, 4];
 
PrivateKey._oldVersionDetect = function (obj) {
	assert.func(obj.toPublic);
	assert.func(obj.createSign);
	if (obj.derive)
		return ([1, 3]);
	if (obj.defaultHashAlgorithm)
		return ([1, 2]);
	if (obj.formats['auto'])
		return ([1, 1]);
	return ([1, 0]);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/signature.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/signature.js

Statements: 12.96% (21 / 162)      Branches: 0% (0 / 65)      Functions: 0% (0 / 10)      Lines: 12.96% (21 / 162)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247    1   1 1 1 1 1 1 1   1 1   1                                 1                                                                                                                                                       1         1                                                                                 1                                       1                       1                             1                                                 1                     1   1              
// Copyright 2015 Joyent, Inc.
 
module.exports = Signature;
 
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var errs = require('./errors');
var utils = require('./utils');
var asn1 = require('asn1');
var SSHBuffer = require('./ssh-buffer');
 
var InvalidAlgorithmError = errs.InvalidAlgorithmError;
var SignatureParseError = errs.SignatureParseError;
 
function Signature(opts) {
	assert.object(opts, 'options');
	assert.arrayOfObject(opts.parts, 'options.parts');
	assert.string(opts.type, 'options.type');
 
	var partLookup = {};
	for (var i = 0; i < opts.parts.length; ++i) {
		var part = opts.parts[i];
		partLookup[part.name] = part;
	}
 
	this.type = opts.type;
	this.hashAlgorithm = opts.hashAlgo;
	this.parts = opts.parts;
	this.part = partLookup;
}
 
Signature.prototype.toBuffer = function (format) {
	if (format === undefined)
		format = 'asn1';
	assert.string(format, 'format');
 
	var buf;
 
	switch (this.type) {
	case 'rsa':
	case 'ed25519':
		if (format === 'ssh') {
			buf = new SSHBuffer({});
			buf.writeString('ssh-' + this.type);
			buf.writePart(this.part.sig);
			return (buf.toBuffer());
		} else {
			return (this.part.sig.data);
		}
 
	case 'dsa':
	case 'ecdsa':
		var r, s;
		if (format === 'asn1') {
			var der = new asn1.BerWriter();
			der.startSequence();
			r = utils.mpNormalize(this.part.r.data);
			s = utils.mpNormalize(this.part.s.data);
			der.writeBuffer(r, asn1.Ber.Integer);
			der.writeBuffer(s, asn1.Ber.Integer);
			der.endSequence();
			return (der.buffer);
		} else if (format === 'ssh' && this.type === 'dsa') {
			buf = new SSHBuffer({});
			buf.writeString('ssh-dss');
			r = this.part.r.data;
			if (r.length > 20 && r[0] === 0x00)
				r = r.slice(1);
			s = this.part.s.data;
			if (s.length > 20 && s[0] === 0x00)
				s = s.slice(1);
			if ((this.hashAlgorithm &&
			    this.hashAlgorithm !== 'sha1') ||
			    r.length + s.length !== 40) {
				throw (new Error('OpenSSH only supports ' +
				    'DSA signatures with SHA1 hash'));
			}
			buf.writeBuffer(Buffer.concat([r, s]));
			return (buf.toBuffer());
		} else if (format === 'ssh' && this.type === 'ecdsa') {
			var inner = new SSHBuffer({});
			r = this.part.r.data;
			inner.writeBuffer(r);
			inner.writePart(this.part.s);
 
			buf = new SSHBuffer({});
			/* XXX: find a more proper way to do this? */
			var curve;
			if (r[0] === 0x00)
				r = r.slice(1);
			var sz = r.length * 8;
			if (sz === 256)
				curve = 'nistp256';
			else if (sz === 384)
				curve = 'nistp384';
			else if (sz === 528)
				curve = 'nistp521';
			buf.writeString('ecdsa-sha2-' + curve);
			buf.writeBuffer(inner.toBuffer());
			return (buf.toBuffer());
		}
		throw (new Error('Invalid signature format'));
	default:
		throw (new Error('Invalid signature data'));
	}
};
 
Signature.prototype.toString = function (format) {
	assert.optionalString(format, 'format');
	return (this.toBuffer(format).toString('base64'));
};
 
Signature.parse = function (data, type, format) {
	if (typeof (data) === 'string')
		data = new Buffer(data, 'base64');
	assert.buffer(data, 'data');
	assert.string(format, 'format');
	assert.string(type, 'type');
 
	var opts = {};
	opts.type = type.toLowerCase();
	opts.parts = [];
 
	try {
		assert.ok(data.length > 0, 'signature must not be empty');
		switch (opts.type) {
		case 'rsa':
			return (parseOneNum(data, type, format, opts,
			    'ssh-rsa'));
		case 'ed25519':
			return (parseOneNum(data, type, format, opts,
			    'ssh-ed25519'));
 
		case 'dsa':
		case 'ecdsa':
			if (format === 'asn1')
				return (parseDSAasn1(data, type, format, opts));
			else if (opts.type === 'dsa')
				return (parseDSA(data, type, format, opts));
			else
				return (parseECDSA(data, type, format, opts));
 
		default:
			throw (new InvalidAlgorithmError(type));
		}
 
	} catch (e) {
		if (e instanceof InvalidAlgorithmError)
			throw (e);
		throw (new SignatureParseError(type, format, e));
	}
};
 
function parseOneNum(data, type, format, opts, headType) {
	if (format === 'ssh') {
		try {
			var buf = new SSHBuffer({buffer: data});
			var head = buf.readString();
		} catch (e) {
			/* fall through */
		}
		if (head === headType) {
			var sig = buf.readPart();
			assert.ok(buf.atEnd(), 'extra trailing bytes');
			sig.name = 'sig';
			opts.parts.push(sig);
			return (new Signature(opts));
		}
	}
	opts.parts.push({name: 'sig', data: data});
	return (new Signature(opts));
}
 
function parseDSAasn1(data, type, format, opts) {
	var der = new asn1.BerReader(data);
	der.readSequence();
	var r = der.readString(asn1.Ber.Integer, true);
	var s = der.readString(asn1.Ber.Integer, true);
 
	opts.parts.push({name: 'r', data: utils.mpNormalize(r)});
	opts.parts.push({name: 's', data: utils.mpNormalize(s)});
 
	return (new Signature(opts));
}
 
function parseDSA(data, type, format, opts) {
	if (data.length != 40) {
		var buf = new SSHBuffer({buffer: data});
		var d = buf.readBuffer();
		if (d.toString('ascii') === 'ssh-dss')
			d = buf.readBuffer();
		assert.ok(buf.atEnd(), 'extra trailing bytes');
		assert.strictEqual(d.length, 40, 'invalid inner length');
		data = d;
	}
	opts.parts.push({name: 'r', data: data.slice(0, 20)});
	opts.parts.push({name: 's', data: data.slice(20, 40)});
	return (new Signature(opts));
}
 
function parseECDSA(data, type, format, opts) {
	var buf = new SSHBuffer({buffer: data});
 
	var r, s;
	var inner = buf.readBuffer();
	if (inner.toString('ascii').match(/^ecdsa-/)) {
		inner = buf.readBuffer();
		assert.ok(buf.atEnd(), 'extra trailing bytes on outer');
		buf = new SSHBuffer({buffer: inner});
		r = buf.readPart();
	} else {
		r = {data: inner};
	}
 
	s = buf.readPart();
	assert.ok(buf.atEnd(), 'extra trailing bytes');
 
	r.name = 'r';
	s.name = 's';
 
	opts.parts.push(r);
	opts.parts.push(s);
	return (new Signature(opts));
}
 
Signature.isSignature = function (obj, ver) {
	return (utils.isCompatible(obj, Signature, ver));
};
 
/*
 * API versions for Signature:
 * [1,0] -- initial ver
 * [2,0] -- support for rsa in full ssh format, compat with sshpk-agent
 *          hashAlgorithm property
 * [2,1] -- first tagged version
 */
Signature.prototype._sshpkApiVersion = [2, 1];
 
Signature._oldVersionDetect = function (obj) {
	assert.func(obj.toBuffer);
	if (obj.hasOwnProperty('hashAlgorithm'))
		return ([2, 0]);
	return ([1, 0]);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/ssh-buffer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/ssh-buffer.js

Statements: 24.21% (23 / 95)      Branches: 0% (0 / 10)      Functions: 0% (0 / 21)      Lines: 24.21% (23 / 95)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150    1   1   1                   1       1       1       1       1             1       1                     1       1                     1           1               1         1                 1       1               1             1                               1           1       1              
// Copyright 2015 Joyent, Inc.
 
module.exports = SSHBuffer;
 
var assert = require('assert-plus');
 
function SSHBuffer(opts) {
	assert.object(opts, 'options');
	if (opts.buffer !== undefined)
		assert.buffer(opts.buffer, 'options.buffer');
 
	this._size = opts.buffer ? opts.buffer.length : 1024;
	this._buffer = opts.buffer || (new Buffer(this._size));
	this._offset = 0;
}
 
SSHBuffer.prototype.toBuffer = function () {
	return (this._buffer.slice(0, this._offset));
};
 
SSHBuffer.prototype.atEnd = function () {
	return (this._offset >= this._buffer.length);
};
 
SSHBuffer.prototype.remainder = function () {
	return (this._buffer.slice(this._offset));
};
 
SSHBuffer.prototype.skip = function (n) {
	this._offset += n;
};
 
SSHBuffer.prototype.expand = function () {
	this._size *= 2;
	var buf = new Buffer(this._size);
	this._buffer.copy(buf, 0);
	this._buffer = buf;
};
 
SSHBuffer.prototype.readPart = function () {
	return ({data: this.readBuffer()});
};
 
SSHBuffer.prototype.readBuffer = function () {
	var len = this._buffer.readUInt32BE(this._offset);
	this._offset += 4;
	assert.ok(this._offset + len <= this._buffer.length,
	    'length out of bounds at +0x' + this._offset.toString(16) +
	    ' (data truncated?)');
	var buf = this._buffer.slice(this._offset, this._offset + len);
	this._offset += len;
	return (buf);
};
 
SSHBuffer.prototype.readString = function () {
	return (this.readBuffer().toString());
};
 
SSHBuffer.prototype.readCString = function () {
	var offset = this._offset;
	while (offset < this._buffer.length &&
	    this._buffer[offset] !== 0x00)
		offset++;
	assert.ok(offset < this._buffer.length, 'c string does not terminate');
	var str = this._buffer.slice(this._offset, offset).toString();
	this._offset = offset + 1;
	return (str);
};
 
SSHBuffer.prototype.readInt = function () {
	var v = this._buffer.readUInt32BE(this._offset);
	this._offset += 4;
	return (v);
};
 
SSHBuffer.prototype.readInt64 = function () {
	assert.ok(this._offset + 8 < this._buffer.length,
	    'buffer not long enough to read Int64');
	var v = this._buffer.slice(this._offset, this._offset + 8);
	this._offset += 8;
	return (v);
};
 
SSHBuffer.prototype.readChar = function () {
	var v = this._buffer[this._offset++];
	return (v);
};
 
SSHBuffer.prototype.writeBuffer = function (buf) {
	while (this._offset + 4 + buf.length > this._size)
		this.expand();
	this._buffer.writeUInt32BE(buf.length, this._offset);
	this._offset += 4;
	buf.copy(this._buffer, this._offset);
	this._offset += buf.length;
};
 
SSHBuffer.prototype.writeString = function (str) {
	this.writeBuffer(new Buffer(str, 'utf8'));
};
 
SSHBuffer.prototype.writeCString = function (str) {
	while (this._offset + 1 + str.length > this._size)
		this.expand();
	this._buffer.write(str, this._offset);
	this._offset += str.length;
	this._buffer[this._offset++] = 0;
};
 
SSHBuffer.prototype.writeInt = function (v) {
	while (this._offset + 4 > this._size)
		this.expand();
	this._buffer.writeUInt32BE(v, this._offset);
	this._offset += 4;
};
 
SSHBuffer.prototype.writeInt64 = function (v) {
	assert.buffer(v, 'value');
	if (v.length > 8) {
		var lead = v.slice(0, v.length - 8);
		for (var i = 0; i < lead.length; ++i) {
			assert.strictEqual(lead[i], 0,
			    'must fit in 64 bits of precision');
		}
		v = v.slice(v.length - 8, v.length);
	}
	while (this._offset + 8 > this._size)
		this.expand();
	v.copy(this._buffer, this._offset);
	this._offset += 8;
};
 
SSHBuffer.prototype.writeChar = function (v) {
	while (this._offset + 1 > this._size)
		this.expand();
	this._buffer[this._offset++] = v;
};
 
SSHBuffer.prototype.writePart = function (p) {
	this.writeBuffer(p.data);
};
 
SSHBuffer.prototype.write = function (buf) {
	while (this._offset + buf.length > this._size)
		this.expand();
	buf.copy(this._buffer, this._offset);
	this._offset += buf.length;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/utils.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/utils.js

Statements: 9.38% (18 / 192)      Branches: 0% (0 / 89)      Functions: 0% (0 / 11)      Lines: 9.38% (18 / 192)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290    1                         1 1 1   1   1                                                 1                                                     1       1   1                                                               1                             1                                                       1                                                   1                         1           1                                   1                                                             1                                                                                  
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	bufferSplit: bufferSplit,
	addRSAMissing: addRSAMissing,
	calculateDSAPublic: calculateDSAPublic,
	mpNormalize: mpNormalize,
	ecNormalize: ecNormalize,
	countZeros: countZeros,
	assertCompatible: assertCompatible,
	isCompatible: isCompatible,
	opensslKeyDeriv: opensslKeyDeriv,
	opensshCipherInfo: opensshCipherInfo
};
 
var assert = require('assert-plus');
var PrivateKey = require('./private-key');
var crypto = require('crypto');
 
var MAX_CLASS_DEPTH = 3;
 
function isCompatible(obj, klass, needVer) {
	if (obj === null || typeof (obj) !== 'object')
		return (false);
	if (needVer === undefined)
		needVer = klass.prototype._sshpkApiVersion;
	if (obj instanceof klass &&
	    klass.prototype._sshpkApiVersion[0] == needVer[0])
		return (true);
	var proto = Object.getPrototypeOf(obj);
	var depth = 0;
	while (proto.constructor.name !== klass.name) {
		proto = Object.getPrototypeOf(proto);
		if (!proto || ++depth > MAX_CLASS_DEPTH)
			return (false);
	}
	if (proto.constructor.name !== klass.name)
		return (false);
	var ver = proto._sshpkApiVersion;
	if (ver === undefined)
		ver = klass._oldVersionDetect(obj);
	if (ver[0] != needVer[0] || ver[1] < needVer[1])
		return (false);
	return (true);
}
 
function assertCompatible(obj, klass, needVer, name) {
	if (name === undefined)
		name = 'object';
	assert.ok(obj, name + ' must not be null');
	assert.object(obj, name + ' must be an object');
	if (needVer === undefined)
		needVer = klass.prototype._sshpkApiVersion;
	if (obj instanceof klass &&
	    klass.prototype._sshpkApiVersion[0] == needVer[0])
		return;
	var proto = Object.getPrototypeOf(obj);
	var depth = 0;
	while (proto.constructor.name !== klass.name) {
		proto = Object.getPrototypeOf(proto);
		assert.ok(proto && ++depth <= MAX_CLASS_DEPTH,
		    name + ' must be a ' + klass.name + ' instance');
	}
	assert.strictEqual(proto.constructor.name, klass.name,
	    name + ' must be a ' + klass.name + ' instance');
	var ver = proto._sshpkApiVersion;
	if (ver === undefined)
		ver = klass._oldVersionDetect(obj);
	assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1],
	    name + ' must be compatible with ' + klass.name + ' klass ' +
	    'version ' + needVer[0] + '.' + needVer[1]);
}
 
var CIPHER_LEN = {
	'des-ede3-cbc': { key: 7, iv: 8 },
	'aes-128-cbc': { key: 16, iv: 16 }
};
var PKCS5_SALT_LEN = 8;
 
function opensslKeyDeriv(cipher, salt, passphrase, count) {
	assert.buffer(salt, 'salt');
	assert.buffer(passphrase, 'passphrase');
	assert.number(count, 'iteration count');
 
	var clen = CIPHER_LEN[cipher];
	assert.object(clen, 'supported cipher');
 
	salt = salt.slice(0, PKCS5_SALT_LEN);
 
	var D, D_prev, bufs;
	var material = new Buffer(0);
	while (material.length < clen.key + clen.iv) {
		bufs = [];
		if (D_prev)
			bufs.push(D_prev);
		bufs.push(passphrase);
		bufs.push(salt);
		D = Buffer.concat(bufs);
		for (var j = 0; j < count; ++j)
			D = crypto.createHash('md5').update(D).digest();
		material = Buffer.concat([material, D]);
		D_prev = D;
	}
 
	return ({
	    key: material.slice(0, clen.key),
	    iv: material.slice(clen.key, clen.key + clen.iv)
	});
}
 
/* Count leading zero bits on a buffer */
function countZeros(buf) {
	var o = 0, obit = 8;
	while (o < buf.length) {
		var mask = (1 << obit);
		if ((buf[o] & mask) === mask)
			break;
		obit--;
		if (obit < 0) {
			o++;
			obit = 8;
		}
	}
	return (o*8 + (8 - obit) - 1);
}
 
function bufferSplit(buf, chr) {
	assert.buffer(buf);
	assert.string(chr);
 
	var parts = [];
	var lastPart = 0;
	var matches = 0;
	for (var i = 0; i < buf.length; ++i) {
		if (buf[i] === chr.charCodeAt(matches))
			++matches;
		else if (buf[i] === chr.charCodeAt(0))
			matches = 1;
		else
			matches = 0;
 
		if (matches >= chr.length) {
			var newPart = i + 1;
			parts.push(buf.slice(lastPart, newPart - matches));
			lastPart = newPart;
			matches = 0;
		}
	}
	if (lastPart <= buf.length)
		parts.push(buf.slice(lastPart, buf.length));
 
	return (parts);
}
 
function ecNormalize(buf, addZero) {
	assert.buffer(buf);
	if (buf[0] === 0x00 && buf[1] === 0x04) {
		if (addZero)
			return (buf);
		return (buf.slice(1));
	} else if (buf[0] === 0x04) {
		if (!addZero)
			return (buf);
	} else {
		while (buf[0] === 0x00)
			buf = buf.slice(1);
		if (buf[0] === 0x02 || buf[0] === 0x03)
			throw (new Error('Compressed elliptic curve points ' +
			    'are not supported'));
		if (buf[0] !== 0x04)
			throw (new Error('Not a valid elliptic curve point'));
		if (!addZero)
			return (buf);
	}
	var b = new Buffer(buf.length + 1);
	b[0] = 0x0;
	buf.copy(b, 1);
	return (b);
}
 
function mpNormalize(buf) {
	assert.buffer(buf);
	while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00)
		buf = buf.slice(1);
	if ((buf[0] & 0x80) === 0x80) {
		var b = new Buffer(buf.length + 1);
		b[0] = 0x00;
		buf.copy(b, 1);
		buf = b;
	}
	return (buf);
}
 
function bigintToMpBuf(bigint) {
	var buf = new Buffer(bigint.toByteArray());
	buf = mpNormalize(buf);
	return (buf);
}
 
function calculateDSAPublic(g, p, x) {
	assert.buffer(g);
	assert.buffer(p);
	assert.buffer(x);
	try {
		var bigInt = require('jsbn').BigInteger;
	} catch (e) {
		throw (new Error('To load a PKCS#8 format DSA private key, ' +
		    'the node jsbn library is required.'));
	}
	g = new bigInt(g);
	p = new bigInt(p);
	x = new bigInt(x);
	var y = g.modPow(x, p);
	var ybuf = bigintToMpBuf(y);
	return (ybuf);
}
 
function addRSAMissing(key) {
	assert.object(key);
	assertCompatible(key, PrivateKey, [1, 1]);
	try {
		var bigInt = require('jsbn').BigInteger;
	} catch (e) {
		throw (new Error('To write a PEM private key from ' +
		    'this source, the node jsbn lib is required.'));
	}
 
	var d = new bigInt(key.part.d.data);
	var buf;
 
	if (!key.part.dmodp) {
		var p = new bigInt(key.part.p.data);
		var dmodp = d.mod(p.subtract(1));
 
		buf = bigintToMpBuf(dmodp);
		key.part.dmodp = {name: 'dmodp', data: buf};
		key.parts.push(key.part.dmodp);
	}
	if (!key.part.dmodq) {
		var q = new bigInt(key.part.q.data);
		var dmodq = d.mod(q.subtract(1));
 
		buf = bigintToMpBuf(dmodq);
		key.part.dmodq = {name: 'dmodq', data: buf};
		key.parts.push(key.part.dmodq);
	}
}
 
function opensshCipherInfo(cipher) {
	var inf = {};
	switch (cipher) {
	case '3des-cbc':
		inf.keySize = 24;
		inf.blockSize = 8;
		inf.opensslName = 'des-ede3-cbc';
		break;
	case 'blowfish-cbc':
		inf.keySize = 16;
		inf.blockSize = 8;
		inf.opensslName = 'bf-cbc';
		break;
	case 'aes128-cbc':
	case 'aes128-ctr':
	case 'aes128-gcm@openssh.com':
		inf.keySize = 16;
		inf.blockSize = 16;
		inf.opensslName = 'aes-128-' + cipher.slice(7, 10);
		break;
	case 'aes192-cbc':
	case 'aes192-ctr':
	case 'aes192-gcm@openssh.com':
		inf.keySize = 24;
		inf.blockSize = 16;
		inf.opensslName = 'aes-192-' + cipher.slice(7, 10);
		break;
	case 'aes256-cbc':
	case 'aes256-ctr':
	case 'aes256-gcm@openssh.com':
		inf.keySize = 32;
		inf.blockSize = 16;
		inf.opensslName = 'aes-256-' + cipher.slice(7, 10);
		break;
	default:
		throw (new Error(
		    'Unsupported openssl cipher "' + cipher + '"'));
	}
	return (inf);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/

Statements: 12.89% (204 / 1583)      Branches: 0% (0 / 543)      Functions: 5.38% (5 / 93)      Lines: 12.83% (203 / 1582)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/
File Statements Branches Functions Lines
auto.js 24.49% (12 / 49) 0% (0 / 39) 0% (0 / 4) 24.49% (12 / 49)
openssh-cert.js 13.61% (26 / 191) 0% (0 / 70) 6.67% (1 / 15) 13.16% (25 / 190)
pem.js 13.27% (15 / 113) 0% (0 / 55) 0% (0 / 3) 13.27% (15 / 113)
pkcs1.js 15.61% (27 / 173) 0% (0 / 33) 0% (0 / 17) 15.61% (27 / 173)
pkcs8.js 9.75% (27 / 277) 0% (0 / 56) 0% (0 / 19) 9.75% (27 / 277)
rfc4253.js 11.83% (11 / 93) 0% (0 / 54) 0% (0 / 4) 11.83% (11 / 93)
ssh-private.js 9.83% (17 / 173) 0% (0 / 48) 0% (0 / 5) 9.83% (17 / 173)
ssh.js 18.64% (11 / 59) 0% (0 / 22) 0% (0 / 2) 18.64% (11 / 59)
x509-pem.js 29.17% (14 / 48) 0% (0 / 6) 0% (0 / 2) 29.17% (14 / 48)
x509.js 10.81% (44 / 407) 0% (0 / 160) 18.18% (4 / 22) 10.81% (44 / 407)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/auto.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/auto.js

Statements: 24.49% (12 / 49)      Branches: 0% (0 / 39)      Functions: 0% (0 / 4)      Lines: 24.49% (12 / 49)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75    1         1 1 1 1   1 1 1   1                                         1                           1                                     1        
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	read: read,
	write: write
};
 
var assert = require('assert-plus');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
 
var pem = require('./pem');
var ssh = require('./ssh');
var rfc4253 = require('./rfc4253');
 
function read(buf, options) {
	if (typeof (buf) === 'string') {
		if (buf.trim().match(/^[-]+[ ]*BEGIN/))
			return (pem.read(buf, options));
		if (buf.match(/^\s*ssh-[a-z]/))
			return (ssh.read(buf, options));
		if (buf.match(/^\s*ecdsa-/))
			return (ssh.read(buf, options));
		buf = new Buffer(buf, 'binary');
	} else {
		assert.buffer(buf);
		if (findPEMHeader(buf))
			return (pem.read(buf, options));
		if (findSSHHeader(buf))
			return (ssh.read(buf, options));
	}
	if (buf.readUInt32BE(0) < buf.length)
		return (rfc4253.read(buf, options));
	throw (new Error('Failed to auto-detect format of key'));
}
 
function findSSHHeader(buf) {
	var offset = 0;
	while (offset < buf.length &&
	    (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
		++offset;
	if (offset + 4 <= buf.length &&
	    buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
		return (true);
	if (offset + 6 <= buf.length &&
	    buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
		return (true);
	return (false);
}
 
function findPEMHeader(buf) {
	var offset = 0;
	while (offset < buf.length &&
	    (buf[offset] === 32 || buf[offset] === 10))
		++offset;
	if (buf[offset] !== 45)
		return (false);
	while (offset < buf.length &&
	    (buf[offset] === 45))
		++offset;
	while (offset < buf.length &&
	    (buf[offset] === 32))
		++offset;
	if (offset + 5 > buf.length ||
	    buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
		return (false);
	return (true);
}
 
function write(key, options) {
	throw (new Error('"auto" format cannot be used for writing'));
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/openssh-cert.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/openssh-cert.js

Statements: 13.61% (26 / 191)      Branches: 0% (0 / 70)      Functions: 6.67% (1 / 15)      Lines: 13.16% (25 / 190)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291    1                     1 1 1 1 1 1 1 1 1 1 1   1               1       2   1   1                           1                                                                                                                                                                                             1                 1                       1                                     1                       1                                                                                                                               1                       1                        
// Copyright 2016 Joyent, Inc.
 
module.exports = {
	read: read,
	verify: verify,
	sign: sign,
	write: write,
 
	/* Internal private API */
	fromBuffer: fromBuffer,
	toBuffer: toBuffer
};
 
var assert = require('assert-plus');
var SSHBuffer = require('../ssh-buffer');
var crypto = require('crypto');
var algs = require('../algs');
var Key = require('../key');
var PrivateKey = require('../private-key');
var Identity = require('../identity');
var rfc4253 = require('./rfc4253');
var Signature = require('../signature');
var utils = require('../utils');
var Certificate = require('../certificate');
 
function verify(cert, key) {
	/*
	 * We always give an issuerKey, so if our verify() is being called then
	 * there was no signature. Return false.
	 */
	return (false);
}
 
var TYPES = {
	'user': 1,
	'host': 2
};
Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; });
 
var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/;
 
function read(buf, options) {
	if (Buffer.isBuffer(buf))
		buf = buf.toString('ascii');
	var parts = buf.trim().split(/[ \t\n]+/g);
	if (parts.length < 2 || parts.length > 3)
		throw (new Error('Not a valid SSH certificate line'));
 
	var algo = parts[0];
	var data = parts[1];
 
	data = new Buffer(data, 'base64');
	return (fromBuffer(data, algo));
}
 
function fromBuffer(data, algo, partial) {
	var sshbuf = new SSHBuffer({ buffer: data });
	var innerAlgo = sshbuf.readString();
	if (algo !== undefined && innerAlgo !== algo)
		throw (new Error('SSH certificate algorithm mismatch'));
	if (algo === undefined)
		algo = innerAlgo;
 
	var cert = {};
	cert.signatures = {};
	cert.signatures.openssh = {};
 
	cert.signatures.openssh.nonce = sshbuf.readBuffer();
 
	var key = {};
	var parts = (key.parts = []);
	key.type = getAlg(algo);
 
	var partCount = algs.info[key.type].parts.length;
	while (parts.length < partCount)
		parts.push(sshbuf.readPart());
	assert.ok(parts.length >= 1, 'key must have at least one part');
 
	var algInfo = algs.info[key.type];
	if (key.type === 'ecdsa') {
		var res = ECDSA_ALGO.exec(algo);
		assert.ok(res !== null);
		assert.strictEqual(res[1], parts[0].data.toString());
	}
 
	for (var i = 0; i < algInfo.parts.length; ++i) {
		parts[i].name = algInfo.parts[i];
		if (parts[i].name !== 'curve' &&
		    algInfo.normalize !== false) {
			var p = parts[i];
			p.data = utils.mpNormalize(p.data);
		}
	}
 
	cert.subjectKey = new Key(key);
 
	cert.serial = sshbuf.readInt64();
 
	var type = TYPES[sshbuf.readInt()];
	assert.string(type, 'valid cert type');
 
	cert.signatures.openssh.keyId = sshbuf.readString();
 
	var principals = [];
	var pbuf = sshbuf.readBuffer();
	var psshbuf = new SSHBuffer({ buffer: pbuf });
	while (!psshbuf.atEnd())
		principals.push(psshbuf.readString());
	if (principals.length === 0)
		principals = ['*'];
 
	cert.subjects = principals.map(function (pr) {
		if (type === 'user')
			return (Identity.forUser(pr));
		else if (type === 'host')
			return (Identity.forHost(pr));
		throw (new Error('Unknown identity type ' + type));
	});
 
	cert.validFrom = int64ToDate(sshbuf.readInt64());
	cert.validUntil = int64ToDate(sshbuf.readInt64());
 
	cert.signatures.openssh.critical = sshbuf.readBuffer();
	cert.signatures.openssh.exts = sshbuf.readBuffer();
 
	/* reserved */
	sshbuf.readBuffer();
 
	var signingKeyBuf = sshbuf.readBuffer();
	cert.issuerKey = rfc4253.read(signingKeyBuf);
 
	/*
	 * OpenSSH certs don't give the identity of the issuer, just their
	 * public key. So, we use an Identity that matches anything. The
	 * isSignedBy() function will later tell you if the key matches.
	 */
	cert.issuer = Identity.forHost('**');
 
	var sigBuf = sshbuf.readBuffer();
	cert.signatures.openssh.signature =
	    Signature.parse(sigBuf, cert.issuerKey.type, 'ssh');
 
	if (partial !== undefined) {
		partial.remainder = sshbuf.remainder();
		partial.consumed = sshbuf._offset;
	}
 
	return (new Certificate(cert));
}
 
function int64ToDate(buf) {
	var i = buf.readUInt32BE(0) * 4294967296;
	i += buf.readUInt32BE(4);
	var d = new Date();
	d.setTime(i * 1000);
	d.sourceInt64 = buf;
	return (d);
}
 
function dateToInt64(date) {
	if (date.sourceInt64 !== undefined)
		return (date.sourceInt64);
	var i = Math.round(date.getTime() / 1000);
	var upper = Math.floor(i / 4294967296);
	var lower = Math.floor(i % 4294967296);
	var buf = new Buffer(8);
	buf.writeUInt32BE(upper, 0);
	buf.writeUInt32BE(lower, 4);
	return (buf);
}
 
function sign(cert, key) {
	if (cert.signatures.openssh === undefined)
		cert.signatures.openssh = {};
	try {
		var blob = toBuffer(cert, true);
	} catch (e) {
		delete (cert.signatures.openssh);
		return (false);
	}
	var sig = cert.signatures.openssh;
	var hashAlgo = undefined;
	if (key.type === 'rsa' || key.type === 'dsa')
		hashAlgo = 'sha1';
	var signer = key.createSign(hashAlgo);
	signer.write(blob);
	sig.signature = signer.sign();
	return (true);
}
 
function write(cert, options) {
	if (options === undefined)
		options = {};
 
	var blob = toBuffer(cert);
	var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64');
	if (options.comment)
		out = out + ' ' + options.comment;
	return (out);
}
 
 
function toBuffer(cert, noSig) {
	assert.object(cert.signatures.openssh, 'signature for openssh format');
	var sig = cert.signatures.openssh;
 
	if (sig.nonce === undefined)
		sig.nonce = crypto.randomBytes(16);
	var buf = new SSHBuffer({});
	buf.writeString(getCertType(cert.subjectKey));
	buf.writeBuffer(sig.nonce);
 
	var key = cert.subjectKey;
	var algInfo = algs.info[key.type];
	algInfo.parts.forEach(function (part) {
		buf.writePart(key.part[part]);
	});
 
	buf.writeInt64(cert.serial);
 
	var type = cert.subjects[0].type;
	assert.notStrictEqual(type, 'unknown');
	cert.subjects.forEach(function (id) {
		assert.strictEqual(id.type, type);
	});
	type = TYPES[type];
	buf.writeInt(type);
 
	if (sig.keyId === undefined) {
		sig.keyId = cert.subjects[0].type + '_' +
		    (cert.subjects[0].uid || cert.subjects[0].hostname);
	}
	buf.writeString(sig.keyId);
 
	var sub = new SSHBuffer({});
	cert.subjects.forEach(function (id) {
		if (type === TYPES.host)
			sub.writeString(id.hostname);
		else if (type === TYPES.user)
			sub.writeString(id.uid);
	});
	buf.writeBuffer(sub.toBuffer());
 
	buf.writeInt64(dateToInt64(cert.validFrom));
	buf.writeInt64(dateToInt64(cert.validUntil));
 
	if (sig.critical === undefined)
		sig.critical = new Buffer(0);
	buf.writeBuffer(sig.critical);
 
	if (sig.exts === undefined)
		sig.exts = new Buffer(0);
	buf.writeBuffer(sig.exts);
 
	/* reserved */
	buf.writeBuffer(new Buffer(0));
 
	sub = rfc4253.write(cert.issuerKey);
	buf.writeBuffer(sub);
 
	if (!noSig)
		buf.writeBuffer(sig.signature.toBuffer('ssh'));
 
	return (buf.toBuffer());
}
 
function getAlg(certType) {
	if (certType === 'ssh-rsa-cert-v01@openssh.com')
		return ('rsa');
	if (certType === 'ssh-dss-cert-v01@openssh.com')
		return ('dsa');
	if (certType.match(ECDSA_ALGO))
		return ('ecdsa');
	if (certType === 'ssh-ed25519-cert-v01@openssh.com')
		return ('ed25519');
	throw (new Error('Unsupported cert type ' + certType));
}
 
function getCertType(key) {
	if (key.type === 'rsa')
		return ('ssh-rsa-cert-v01@openssh.com');
	if (key.type === 'dsa')
		return ('ssh-dss-cert-v01@openssh.com');
	if (key.type === 'ecdsa')
		return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com');
	if (key.type === 'ed25519')
		return ('ssh-ed25519-cert-v01@openssh.com');
	throw (new Error('Unsupported key type ' + key.type));
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/pem.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/pem.js

Statements: 13.27% (15 / 113)      Branches: 0% (0 / 55)      Functions: 0% (0 / 3)      Lines: 13.27% (15 / 113)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188    1         1 1 1 1 1 1 1   1 1 1 1   1           1                                                                                                                                                                                                                       1                                                                                                          
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	read: read,
	write: write
};
 
var assert = require('assert-plus');
var asn1 = require('asn1');
var crypto = require('crypto');
var algs = require('../algs');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
 
var pkcs1 = require('./pkcs1');
var pkcs8 = require('./pkcs8');
var sshpriv = require('./ssh-private');
var rfc4253 = require('./rfc4253');
 
var errors = require('../errors');
 
/*
 * For reading we support both PKCS#1 and PKCS#8. If we find a private key,
 * we just take the public component of it and use that.
 */
function read(buf, options, forceType) {
	var input = buf;
	if (typeof (buf) !== 'string') {
		assert.buffer(buf, 'buf');
		buf = buf.toString('ascii');
	}
 
	var lines = buf.trim().split('\n');
 
	var m = lines[0].match(/*JSSTYLED*/
	    /[-]+[ ]*BEGIN ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
	assert.ok(m, 'invalid PEM header');
 
	var m2 = lines[lines.length - 1].match(/*JSSTYLED*/
	    /[-]+[ ]*END ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
	assert.ok(m2, 'invalid PEM footer');
 
	/* Begin and end banners must match key type */
	assert.equal(m[2], m2[2]);
	var type = m[2].toLowerCase();
 
	var alg;
	if (m[1]) {
		/* They also must match algorithms, if given */
		assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
		alg = m[1].trim();
	}
 
	var headers = {};
	while (true) {
		lines = lines.slice(1);
		m = lines[0].match(/*JSSTYLED*/
		    /^([A-Za-z0-9-]+): (.+)$/);
		if (!m)
			break;
		headers[m[1].toLowerCase()] = m[2];
	}
 
	var cipher, key, iv;
	if (headers['proc-type']) {
		var parts = headers['proc-type'].split(',');
		if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
			if (typeof (options.passphrase) === 'string') {
				options.passphrase = new Buffer(
				    options.passphrase, 'utf-8');
			}
			if (!Buffer.isBuffer(options.passphrase)) {
				throw (new errors.KeyEncryptedError(
				    options.filename, 'PEM'));
			} else {
				parts = headers['dek-info'].split(',');
				assert.ok(parts.length === 2);
				cipher = parts[0].toLowerCase();
				iv = new Buffer(parts[1], 'hex');
				key = utils.opensslKeyDeriv(cipher, iv,
				    options.passphrase, 1).key;
			}
		}
	}
 
	/* Chop off the first and last lines */
	lines = lines.slice(0, -1).join('');
	buf = new Buffer(lines, 'base64');
 
	if (cipher && key && iv) {
		var cipherStream = crypto.createDecipheriv(cipher, key, iv);
		var chunk, chunks = [];
		cipherStream.once('error', function (e) {
			if (e.toString().indexOf('bad decrypt') !== -1) {
				throw (new Error('Incorrect passphrase ' +
				    'supplied, could not decrypt key'));
			}
			throw (e);
		});
		cipherStream.write(buf);
		cipherStream.end();
		while ((chunk = cipherStream.read()) !== null)
			chunks.push(chunk);
		buf = Buffer.concat(chunks);
	}
 
	/* The new OpenSSH internal format abuses PEM headers */
	if (alg && alg.toLowerCase() === 'openssh')
		return (sshpriv.readSSHPrivate(type, buf, options));
	if (alg && alg.toLowerCase() === 'ssh2')
		return (rfc4253.readType(type, buf, options));
 
	var der = new asn1.BerReader(buf);
	der.originalInput = input;
 
	/*
	 * All of the PEM file types start with a sequence tag, so chop it
	 * off here
	 */
	der.readSequence();
 
	/* PKCS#1 type keys name an algorithm in the banner explicitly */
	if (alg) {
		if (forceType)
			assert.strictEqual(forceType, 'pkcs1');
		return (pkcs1.readPkcs1(alg, type, der));
	} else {
		if (forceType)
			assert.strictEqual(forceType, 'pkcs8');
		return (pkcs8.readPkcs8(alg, type, der));
	}
}
 
function write(key, options, type) {
	assert.object(key);
 
	var alg = {'ecdsa': 'EC', 'rsa': 'RSA', 'dsa': 'DSA'}[key.type];
	var header;
 
	var der = new asn1.BerWriter();
 
	if (PrivateKey.isPrivateKey(key)) {
		if (type && type === 'pkcs8') {
			header = 'PRIVATE KEY';
			pkcs8.writePkcs8(der, key);
		} else {
			if (type)
				assert.strictEqual(type, 'pkcs1');
			header = alg + ' PRIVATE KEY';
			pkcs1.writePkcs1(der, key);
		}
 
	} else if (Key.isKey(key)) {
		if (type && type === 'pkcs1') {
			header = alg + ' PUBLIC KEY';
			pkcs1.writePkcs1(der, key);
		} else {
			if (type)
				assert.strictEqual(type, 'pkcs8');
			header = 'PUBLIC KEY';
			pkcs8.writePkcs8(der, key);
		}
 
	} else {
		throw (new Error('key is not a Key or PrivateKey'));
	}
 
	var tmp = der.buffer.toString('base64');
	var len = tmp.length + (tmp.length / 64) +
	    18 + 16 + header.length*2 + 10;
	var buf = new Buffer(len);
	var o = 0;
	o += buf.write('-----BEGIN ' + header + '-----\n', o);
	for (var i = 0; i < tmp.length; ) {
		var limit = i + 64;
		if (limit > tmp.length)
			limit = tmp.length;
		o += buf.write(tmp.slice(i, limit), o);
		buf[o++] = 10;
		i = limit;
	}
	o += buf.write('-----END ' + header + '-----\n', o);
 
	return (buf.slice(0, o));
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/pkcs1.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/pkcs1.js

Statements: 15.61% (27 / 173)      Branches: 0% (0 / 33)      Functions: 0% (0 / 17)      Lines: 15.61% (27 / 173)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322    1             1 1 1 1   1 1 1   1 1   1       1         1           1                                                   1                                 1                                                               1                                                 1                                     1                                                                   1                                                     1                                                         1         1                                 1                       1             1                             1                                        
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	read: read,
	readPkcs1: readPkcs1,
	write: write,
	writePkcs1: writePkcs1
};
 
var assert = require('assert-plus');
var asn1 = require('asn1');
var algs = require('../algs');
var utils = require('../utils');
 
var Key = require('../key');
var PrivateKey = require('../private-key');
var pem = require('./pem');
 
var pkcs8 = require('./pkcs8');
var readECDSACurve = pkcs8.readECDSACurve;
 
function read(buf, options) {
	return (pem.read(buf, options, 'pkcs1'));
}
 
function write(key, options) {
	return (pem.write(key, options, 'pkcs1'));
}
 
/* Helper to read in a single mpint */
function readMPInt(der, nm) {
	assert.strictEqual(der.peek(), asn1.Ber.Integer,
	    nm + ' is not an Integer');
	return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
}
 
function readPkcs1(alg, type, der) {
	switch (alg) {
	case 'RSA':
		if (type === 'public')
			return (readPkcs1RSAPublic(der));
		else if (type === 'private')
			return (readPkcs1RSAPrivate(der));
		throw (new Error('Unknown key type: ' + type));
	case 'DSA':
		if (type === 'public')
			return (readPkcs1DSAPublic(der));
		else if (type === 'private')
			return (readPkcs1DSAPrivate(der));
		throw (new Error('Unknown key type: ' + type));
	case 'EC':
	case 'ECDSA':
		if (type === 'private')
			return (readPkcs1ECDSAPrivate(der));
		else if (type === 'public')
			return (readPkcs1ECDSAPublic(der));
		throw (new Error('Unknown key type: ' + type));
	default:
		throw (new Error('Unknown key algo: ' + alg));
	}
}
 
function readPkcs1RSAPublic(der) {
	// modulus and exponent
	var n = readMPInt(der, 'modulus');
	var e = readMPInt(der, 'exponent');
 
	// now, make the key
	var key = {
		type: 'rsa',
		parts: [
			{ name: 'e', data: e },
			{ name: 'n', data: n }
		]
	};
 
	return (new Key(key));
}
 
function readPkcs1RSAPrivate(der) {
	var version = readMPInt(der, 'version');
	assert.strictEqual(version[0], 0);
 
	// modulus then public exponent
	var n = readMPInt(der, 'modulus');
	var e = readMPInt(der, 'public exponent');
	var d = readMPInt(der, 'private exponent');
	var p = readMPInt(der, 'prime1');
	var q = readMPInt(der, 'prime2');
	var dmodp = readMPInt(der, 'exponent1');
	var dmodq = readMPInt(der, 'exponent2');
	var iqmp = readMPInt(der, 'iqmp');
 
	// now, make the key
	var key = {
		type: 'rsa',
		parts: [
			{ name: 'n', data: n },
			{ name: 'e', data: e },
			{ name: 'd', data: d },
			{ name: 'iqmp', data: iqmp },
			{ name: 'p', data: p },
			{ name: 'q', data: q },
			{ name: 'dmodp', data: dmodp },
			{ name: 'dmodq', data: dmodq }
		]
	};
 
	return (new PrivateKey(key));
}
 
function readPkcs1DSAPrivate(der) {
	var version = readMPInt(der, 'version');
	assert.strictEqual(version.readUInt8(0), 0);
 
	var p = readMPInt(der, 'p');
	var q = readMPInt(der, 'q');
	var g = readMPInt(der, 'g');
	var y = readMPInt(der, 'y');
	var x = readMPInt(der, 'x');
 
	// now, make the key
	var key = {
		type: 'dsa',
		parts: [
			{ name: 'p', data: p },
			{ name: 'q', data: q },
			{ name: 'g', data: g },
			{ name: 'y', data: y },
			{ name: 'x', data: x }
		]
	};
 
	return (new PrivateKey(key));
}
 
function readPkcs1DSAPublic(der) {
	var y = readMPInt(der, 'y');
	var p = readMPInt(der, 'p');
	var q = readMPInt(der, 'q');
	var g = readMPInt(der, 'g');
 
	var key = {
		type: 'dsa',
		parts: [
			{ name: 'y', data: y },
			{ name: 'p', data: p },
			{ name: 'q', data: q },
			{ name: 'g', data: g }
		]
	};
 
	return (new Key(key));
}
 
function readPkcs1ECDSAPublic(der) {
	der.readSequence();
 
	var oid = der.readOID();
	assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey');
 
	var curveOid = der.readOID();
 
	var curve;
	var curves = Object.keys(algs.curves);
	for (var j = 0; j < curves.length; ++j) {
		var c = curves[j];
		var cd = algs.curves[c];
		if (cd.pkcs8oid === curveOid) {
			curve = c;
			break;
		}
	}
	assert.string(curve, 'a known ECDSA named curve');
 
	var Q = der.readString(asn1.Ber.BitString, true);
	Q = utils.ecNormalize(Q);
 
	var key = {
		type: 'ecdsa',
		parts: [
			{ name: 'curve', data: new Buffer(curve) },
			{ name: 'Q', data: Q }
		]
	};
 
	return (new Key(key));
}
 
function readPkcs1ECDSAPrivate(der) {
	var version = readMPInt(der, 'version');
	assert.strictEqual(version.readUInt8(0), 1);
 
	// private key
	var d = der.readString(asn1.Ber.OctetString, true);
 
	der.readSequence(0xa0);
	var curve = readECDSACurve(der);
	assert.string(curve, 'a known elliptic curve');
 
	der.readSequence(0xa1);
	var Q = der.readString(asn1.Ber.BitString, true);
	Q = utils.ecNormalize(Q);
 
	var key = {
		type: 'ecdsa',
		parts: [
			{ name: 'curve', data: new Buffer(curve) },
			{ name: 'Q', data: Q },
			{ name: 'd', data: d }
		]
	};
 
	return (new PrivateKey(key));
}
 
function writePkcs1(der, key) {
	der.startSequence();
 
	switch (key.type) {
	case 'rsa':
		if (PrivateKey.isPrivateKey(key))
			writePkcs1RSAPrivate(der, key);
		else
			writePkcs1RSAPublic(der, key);
		break;
	case 'dsa':
		if (PrivateKey.isPrivateKey(key))
			writePkcs1DSAPrivate(der, key);
		else
			writePkcs1DSAPublic(der, key);
		break;
	case 'ecdsa':
		if (PrivateKey.isPrivateKey(key))
			writePkcs1ECDSAPrivate(der, key);
		else
			writePkcs1ECDSAPublic(der, key);
		break;
	default:
		throw (new Error('Unknown key algo: ' + key.type));
	}
 
	der.endSequence();
}
 
function writePkcs1RSAPublic(der, key) {
	der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
}
 
function writePkcs1RSAPrivate(der, key) {
	var ver = new Buffer(1);
	ver[0] = 0;
	der.writeBuffer(ver, asn1.Ber.Integer);
 
	der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
	if (!key.part.dmodp || !key.part.dmodq)
		utils.addRSAMissing(key);
	der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
}
 
function writePkcs1DSAPrivate(der, key) {
	var ver = new Buffer(1);
	ver[0] = 0;
	der.writeBuffer(ver, asn1.Ber.Integer);
 
	der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
}
 
function writePkcs1DSAPublic(der, key) {
	der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
}
 
function writePkcs1ECDSAPublic(der, key) {
	der.startSequence();
 
	der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */
	var curve = key.part.curve.data.toString();
	var curveOid = algs.curves[curve].pkcs8oid;
	assert.string(curveOid, 'a known ECDSA named curve');
	der.writeOID(curveOid);
 
	der.endSequence();
 
	var Q = utils.ecNormalize(key.part.Q.data, true);
	der.writeBuffer(Q, asn1.Ber.BitString);
}
 
function writePkcs1ECDSAPrivate(der, key) {
	var ver = new Buffer(1);
	ver[0] = 1;
	der.writeBuffer(ver, asn1.Ber.Integer);
 
	der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
 
	der.startSequence(0xa0);
	var curve = key.part.curve.data.toString();
	var curveOid = algs.curves[curve].pkcs8oid;
	assert.string(curveOid, 'a known ECDSA named curve');
	der.writeOID(curveOid);
	der.endSequence();
 
	der.startSequence(0xa1);
	var Q = utils.ecNormalize(key.part.Q.data, true);
	der.writeBuffer(Q, asn1.Ber.BitString);
	der.endSequence();
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/pkcs8.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/pkcs8.js

Statements: 9.75% (27 / 277)      Branches: 0% (0 / 56)      Functions: 0% (0 / 19)      Lines: 9.75% (27 / 277)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507    1                   1 1 1 1 1 1 1   1       1         1           1                                                                   1                                             1                                                                     1                                                     1                                                     1                                                                                                                                                                                                 1                                                       1                                   1                                                                             1                                                   1                             1                           1                           1                                                                                       1               1                                            
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	read: read,
	readPkcs8: readPkcs8,
	write: write,
	writePkcs8: writePkcs8,
 
	readECDSACurve: readECDSACurve,
	writeECDSACurve: writeECDSACurve
};
 
var assert = require('assert-plus');
var asn1 = require('asn1');
var algs = require('../algs');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
var pem = require('./pem');
 
function read(buf, options) {
	return (pem.read(buf, options, 'pkcs8'));
}
 
function write(key, options) {
	return (pem.write(key, options, 'pkcs8'));
}
 
/* Helper to read in a single mpint */
function readMPInt(der, nm) {
	assert.strictEqual(der.peek(), asn1.Ber.Integer,
	    nm + ' is not an Integer');
	return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
}
 
function readPkcs8(alg, type, der) {
	/* Private keys in pkcs#8 format have a weird extra int */
	if (der.peek() === asn1.Ber.Integer) {
		assert.strictEqual(type, 'private',
		    'unexpected Integer at start of public key');
		der.readString(asn1.Ber.Integer, true);
	}
 
	der.readSequence();
	var next = der.offset + der.length;
 
	var oid = der.readOID();
	switch (oid) {
	case '1.2.840.113549.1.1.1':
		der._offset = next;
		if (type === 'public')
			return (readPkcs8RSAPublic(der));
		else
			return (readPkcs8RSAPrivate(der));
	case '1.2.840.10040.4.1':
		if (type === 'public')
			return (readPkcs8DSAPublic(der));
		else
			return (readPkcs8DSAPrivate(der));
	case '1.2.840.10045.2.1':
		if (type === 'public')
			return (readPkcs8ECDSAPublic(der));
		else
			return (readPkcs8ECDSAPrivate(der));
	default:
		throw (new Error('Unknown key type OID ' + oid));
	}
}
 
function readPkcs8RSAPublic(der) {
	// bit string sequence
	der.readSequence(asn1.Ber.BitString);
	der.readByte();
	der.readSequence();
 
	// modulus
	var n = readMPInt(der, 'modulus');
	var e = readMPInt(der, 'exponent');
 
	// now, make the key
	var key = {
		type: 'rsa',
		source: der.originalInput,
		parts: [
			{ name: 'e', data: e },
			{ name: 'n', data: n }
		]
	};
 
	return (new Key(key));
}
 
function readPkcs8RSAPrivate(der) {
	der.readSequence(asn1.Ber.OctetString);
	der.readSequence();
 
	var ver = readMPInt(der, 'version');
	assert.equal(ver[0], 0x0, 'unknown RSA private key version');
 
	// modulus then public exponent
	var n = readMPInt(der, 'modulus');
	var e = readMPInt(der, 'public exponent');
	var d = readMPInt(der, 'private exponent');
	var p = readMPInt(der, 'prime1');
	var q = readMPInt(der, 'prime2');
	var dmodp = readMPInt(der, 'exponent1');
	var dmodq = readMPInt(der, 'exponent2');
	var iqmp = readMPInt(der, 'iqmp');
 
	// now, make the key
	var key = {
		type: 'rsa',
		parts: [
			{ name: 'n', data: n },
			{ name: 'e', data: e },
			{ name: 'd', data: d },
			{ name: 'iqmp', data: iqmp },
			{ name: 'p', data: p },
			{ name: 'q', data: q },
			{ name: 'dmodp', data: dmodp },
			{ name: 'dmodq', data: dmodq }
		]
	};
 
	return (new PrivateKey(key));
}
 
function readPkcs8DSAPublic(der) {
	der.readSequence();
 
	var p = readMPInt(der, 'p');
	var q = readMPInt(der, 'q');
	var g = readMPInt(der, 'g');
 
	// bit string sequence
	der.readSequence(asn1.Ber.BitString);
	der.readByte();
 
	var y = readMPInt(der, 'y');
 
	// now, make the key
	var key = {
		type: 'dsa',
		parts: [
			{ name: 'p', data: p },
			{ name: 'q', data: q },
			{ name: 'g', data: g },
			{ name: 'y', data: y }
		]
	};
 
	return (new Key(key));
}
 
function readPkcs8DSAPrivate(der) {
	der.readSequence();
 
	var p = readMPInt(der, 'p');
	var q = readMPInt(der, 'q');
	var g = readMPInt(der, 'g');
 
	der.readSequence(asn1.Ber.OctetString);
	var x = readMPInt(der, 'x');
 
	/* The pkcs#8 format does not include the public key */
	var y = utils.calculateDSAPublic(g, p, x);
 
	var key = {
		type: 'dsa',
		parts: [
			{ name: 'p', data: p },
			{ name: 'q', data: q },
			{ name: 'g', data: g },
			{ name: 'y', data: y },
			{ name: 'x', data: x }
		]
	};
 
	return (new PrivateKey(key));
}
 
function readECDSACurve(der) {
	var curveName, curveNames;
	var j, c, cd;
 
	if (der.peek() === asn1.Ber.OID) {
		var oid = der.readOID();
 
		curveNames = Object.keys(algs.curves);
		for (j = 0; j < curveNames.length; ++j) {
			c = curveNames[j];
			cd = algs.curves[c];
			if (cd.pkcs8oid === oid) {
				curveName = c;
				break;
			}
		}
 
	} else {
		// ECParameters sequence
		der.readSequence();
		var version = der.readString(asn1.Ber.Integer, true);
		assert.strictEqual(version[0], 1, 'ECDSA key not version 1');
 
		var curve = {};
 
		// FieldID sequence
		der.readSequence();
		var fieldTypeOid = der.readOID();
		assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1',
		    'ECDSA key is not from a prime-field');
		var p = curve.p = utils.mpNormalize(
		    der.readString(asn1.Ber.Integer, true));
		/*
		 * p always starts with a 1 bit, so count the zeros to get its
		 * real size.
		 */
		curve.size = p.length * 8 - utils.countZeros(p);
 
		// Curve sequence
		der.readSequence();
		curve.a = utils.mpNormalize(
		    der.readString(asn1.Ber.OctetString, true));
		curve.b = utils.mpNormalize(
		    der.readString(asn1.Ber.OctetString, true));
		if (der.peek() === asn1.Ber.BitString)
			curve.s = der.readString(asn1.Ber.BitString, true);
 
		// Combined Gx and Gy
		curve.G = der.readString(asn1.Ber.OctetString, true);
		assert.strictEqual(curve.G[0], 0x4,
		    'uncompressed G is required');
 
		curve.n = utils.mpNormalize(
		    der.readString(asn1.Ber.Integer, true));
		curve.h = utils.mpNormalize(
		    der.readString(asn1.Ber.Integer, true));
		assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' +
		    'required');
 
		curveNames = Object.keys(algs.curves);
		var ks = Object.keys(curve);
		for (j = 0; j < curveNames.length; ++j) {
			c = curveNames[j];
			cd = algs.curves[c];
			var equal = true;
			for (var i = 0; i < ks.length; ++i) {
				var k = ks[i];
				if (cd[k] === undefined)
					continue;
				if (typeof (cd[k]) === 'object' &&
				    cd[k].equals !== undefined) {
					if (!cd[k].equals(curve[k])) {
						equal = false;
						break;
					}
				} else if (Buffer.isBuffer(cd[k])) {
					if (cd[k].toString('binary')
					    !== curve[k].toString('binary')) {
						equal = false;
						break;
					}
				} else {
					if (cd[k] !== curve[k]) {
						equal = false;
						break;
					}
				}
			}
			if (equal) {
				curveName = c;
				break;
			}
		}
	}
	return (curveName);
}
 
function readPkcs8ECDSAPrivate(der) {
	var curveName = readECDSACurve(der);
	assert.string(curveName, 'a known elliptic curve');
 
	der.readSequence(asn1.Ber.OctetString);
	der.readSequence();
 
	var version = readMPInt(der, 'version');
	assert.equal(version[0], 1, 'unknown version of ECDSA key');
 
	var d = der.readString(asn1.Ber.OctetString, true);
	der.readSequence(0xa1);
 
	var Q = der.readString(asn1.Ber.BitString, true);
	Q = utils.ecNormalize(Q);
 
	var key = {
		type: 'ecdsa',
		parts: [
			{ name: 'curve', data: new Buffer(curveName) },
			{ name: 'Q', data: Q },
			{ name: 'd', data: d }
		]
	};
 
	return (new PrivateKey(key));
}
 
function readPkcs8ECDSAPublic(der) {
	var curveName = readECDSACurve(der);
	assert.string(curveName, 'a known elliptic curve');
 
	var Q = der.readString(asn1.Ber.BitString, true);
	Q = utils.ecNormalize(Q);
 
	var key = {
		type: 'ecdsa',
		parts: [
			{ name: 'curve', data: new Buffer(curveName) },
			{ name: 'Q', data: Q }
		]
	};
 
	return (new Key(key));
}
 
function writePkcs8(der, key) {
	der.startSequence();
 
	if (PrivateKey.isPrivateKey(key)) {
		var sillyInt = new Buffer(1);
		sillyInt[0] = 0x0;
		der.writeBuffer(sillyInt, asn1.Ber.Integer);
	}
 
	der.startSequence();
	switch (key.type) {
	case 'rsa':
		der.writeOID('1.2.840.113549.1.1.1');
		if (PrivateKey.isPrivateKey(key))
			writePkcs8RSAPrivate(key, der);
		else
			writePkcs8RSAPublic(key, der);
		break;
	case 'dsa':
		der.writeOID('1.2.840.10040.4.1');
		if (PrivateKey.isPrivateKey(key))
			writePkcs8DSAPrivate(key, der);
		else
			writePkcs8DSAPublic(key, der);
		break;
	case 'ecdsa':
		der.writeOID('1.2.840.10045.2.1');
		if (PrivateKey.isPrivateKey(key))
			writePkcs8ECDSAPrivate(key, der);
		else
			writePkcs8ECDSAPublic(key, der);
		break;
	default:
		throw (new Error('Unsupported key type: ' + key.type));
	}
 
	der.endSequence();
}
 
function writePkcs8RSAPrivate(key, der) {
	der.writeNull();
	der.endSequence();
 
	der.startSequence(asn1.Ber.OctetString);
	der.startSequence();
 
	var version = new Buffer(1);
	version[0] = 0;
	der.writeBuffer(version, asn1.Ber.Integer);
 
	der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
	if (!key.part.dmodp || !key.part.dmodq)
		utils.addRSAMissing(key);
	der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
 
	der.endSequence();
	der.endSequence();
}
 
function writePkcs8RSAPublic(key, der) {
	der.writeNull();
	der.endSequence();
 
	der.startSequence(asn1.Ber.BitString);
	der.writeByte(0x00);
 
	der.startSequence();
	der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
	der.endSequence();
 
	der.endSequence();
}
 
function writePkcs8DSAPrivate(key, der) {
	der.startSequence();
	der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
	der.endSequence();
 
	der.endSequence();
 
	der.startSequence(asn1.Ber.OctetString);
	der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
	der.endSequence();
}
 
function writePkcs8DSAPublic(key, der) {
	der.startSequence();
	der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
	der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
	der.endSequence();
	der.endSequence();
 
	der.startSequence(asn1.Ber.BitString);
	der.writeByte(0x00);
	der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
	der.endSequence();
}
 
function writeECDSACurve(key, der) {
	var curve = algs.curves[key.curve];
	if (curve.pkcs8oid) {
		/* This one has a name in pkcs#8, so just write the oid */
		der.writeOID(curve.pkcs8oid);
 
	} else {
		// ECParameters sequence
		der.startSequence();
 
		var version = new Buffer(1);
		version.writeUInt8(1, 0);
		der.writeBuffer(version, asn1.Ber.Integer);
 
		// FieldID sequence
		der.startSequence();
		der.writeOID('1.2.840.10045.1.1'); // prime-field
		der.writeBuffer(curve.p, asn1.Ber.Integer);
		der.endSequence();
 
		// Curve sequence
		der.startSequence();
		var a = curve.p;
		if (a[0] === 0x0)
			a = a.slice(1);
		der.writeBuffer(a, asn1.Ber.OctetString);
		der.writeBuffer(curve.b, asn1.Ber.OctetString);
		der.writeBuffer(curve.s, asn1.Ber.BitString);
		der.endSequence();
 
		der.writeBuffer(curve.G, asn1.Ber.OctetString);
		der.writeBuffer(curve.n, asn1.Ber.Integer);
		var h = curve.h;
		if (!h) {
			h = new Buffer(1);
			h[0] = 1;
		}
		der.writeBuffer(h, asn1.Ber.Integer);
 
		// ECParameters
		der.endSequence();
	}
}
 
function writePkcs8ECDSAPublic(key, der) {
	writeECDSACurve(key, der);
	der.endSequence();
 
	var Q = utils.ecNormalize(key.part.Q.data, true);
	der.writeBuffer(Q, asn1.Ber.BitString);
}
 
function writePkcs8ECDSAPrivate(key, der) {
	writeECDSACurve(key, der);
	der.endSequence();
 
	der.startSequence(asn1.Ber.OctetString);
	der.startSequence();
 
	var version = new Buffer(1);
	version[0] = 1;
	der.writeBuffer(version, asn1.Ber.Integer);
 
	der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
 
	der.startSequence(0xa1);
	var Q = utils.ecNormalize(key.part.Q.data, true);
	der.writeBuffer(Q, asn1.Ber.BitString);
	der.endSequence();
 
	der.endSequence();
	der.endSequence();
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/rfc4253.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/rfc4253.js

Statements: 11.83% (11 / 93)      Branches: 0% (0 / 54)      Functions: 0% (0 / 4)      Lines: 11.83% (11 / 93)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148    1                         1 1 1 1 1 1   1                               1                               1                                                                                                                                       1                                                  
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	read: read.bind(undefined, false, undefined),
	readType: read.bind(undefined, false),
	write: write,
	/* semi-private api, used by sshpk-agent */
	readPartial: read.bind(undefined, true),
 
	/* shared with ssh format */
	readInternal: read,
	keyTypeToAlg: keyTypeToAlg,
	algToKeyType: algToKeyType
};
 
var assert = require('assert-plus');
var algs = require('../algs');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
var SSHBuffer = require('../ssh-buffer');
 
function algToKeyType(alg) {
	assert.string(alg);
	if (alg === 'ssh-dss')
		return ('dsa');
	else if (alg === 'ssh-rsa')
		return ('rsa');
	else if (alg === 'ssh-ed25519')
		return ('ed25519');
	else if (alg === 'ssh-curve25519')
		return ('curve25519');
	else if (alg.match(/^ecdsa-sha2-/))
		return ('ecdsa');
	else
		throw (new Error('Unknown algorithm ' + alg));
}
 
function keyTypeToAlg(key) {
	assert.object(key);
	if (key.type === 'dsa')
		return ('ssh-dss');
	else if (key.type === 'rsa')
		return ('ssh-rsa');
	else if (key.type === 'ed25519')
		return ('ssh-ed25519');
	else if (key.type === 'curve25519')
		return ('ssh-curve25519');
	else if (key.type === 'ecdsa')
		return ('ecdsa-sha2-' + key.part.curve.data.toString());
	else
		throw (new Error('Unknown key type ' + key.type));
}
 
function read(partial, type, buf, options) {
	if (typeof (buf) === 'string')
		buf = new Buffer(buf);
	assert.buffer(buf, 'buf');
 
	var key = {};
 
	var parts = key.parts = [];
	var sshbuf = new SSHBuffer({buffer: buf});
 
	var alg = sshbuf.readString();
	assert.ok(!sshbuf.atEnd(), 'key must have at least one part');
 
	key.type = algToKeyType(alg);
 
	var partCount = algs.info[key.type].parts.length;
	if (type && type === 'private')
		partCount = algs.privInfo[key.type].parts.length;
 
	while (!sshbuf.atEnd() && parts.length < partCount)
		parts.push(sshbuf.readPart());
	while (!partial && !sshbuf.atEnd())
		parts.push(sshbuf.readPart());
 
	assert.ok(parts.length >= 1,
	    'key must have at least one part');
	assert.ok(partial || sshbuf.atEnd(),
	    'leftover bytes at end of key');
 
	var Constructor = Key;
	var algInfo = algs.info[key.type];
	if (type === 'private' || algInfo.parts.length !== parts.length) {
		algInfo = algs.privInfo[key.type];
		Constructor = PrivateKey;
	}
	assert.strictEqual(algInfo.parts.length, parts.length);
 
	if (key.type === 'ecdsa') {
		var res = /^ecdsa-sha2-(.+)$/.exec(alg);
		assert.ok(res !== null);
		assert.strictEqual(res[1], parts[0].data.toString());
	}
 
	var normalized = true;
	for (var i = 0; i < algInfo.parts.length; ++i) {
		parts[i].name = algInfo.parts[i];
		if (parts[i].name !== 'curve' &&
		    algInfo.normalize !== false) {
			var p = parts[i];
			var nd = utils.mpNormalize(p.data);
			if (nd !== p.data) {
				p.data = nd;
				normalized = false;
			}
		}
	}
 
	if (normalized)
		key._rfc4253Cache = sshbuf.toBuffer();
 
	if (partial && typeof (partial) === 'object') {
		partial.remainder = sshbuf.remainder();
		partial.consumed = sshbuf._offset;
	}
 
	return (new Constructor(key));
}
 
function write(key, options) {
	assert.object(key);
 
	var alg = keyTypeToAlg(key);
	var i;
 
	var algInfo = algs.info[key.type];
	if (PrivateKey.isPrivateKey(key))
		algInfo = algs.privInfo[key.type];
	var parts = algInfo.parts;
 
	var buf = new SSHBuffer({});
 
	buf.writeString(alg);
 
	for (i = 0; i < parts.length; ++i) {
		var data = key.part[parts[i]].data;
		if (algInfo.normalize !== false)
			data = utils.mpNormalize(data);
		buf.writeBuffer(data);
	}
 
	return (buf.toBuffer());
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/ssh-private.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/ssh-private.js

Statements: 9.83% (17 / 173)      Branches: 0% (0 / 48)      Functions: 0% (0 / 5)      Lines: 9.83% (17 / 173)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263    1           1 1 1 1 1   1 1 1 1 1 1   1   1       1   1                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                              
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	read: read,
	readSSHPrivate: readSSHPrivate,
	write: write
};
 
var assert = require('assert-plus');
var asn1 = require('asn1');
var algs = require('../algs');
var utils = require('../utils');
var crypto = require('crypto');
 
var Key = require('../key');
var PrivateKey = require('../private-key');
var pem = require('./pem');
var rfc4253 = require('./rfc4253');
var SSHBuffer = require('../ssh-buffer');
var errors = require('../errors');
 
var bcrypt;
 
function read(buf, options) {
	return (pem.read(buf, options));
}
 
var MAGIC = 'openssh-key-v1';
 
function readSSHPrivate(type, buf, options) {
	buf = new SSHBuffer({buffer: buf});
 
	var magic = buf.readCString();
	assert.strictEqual(magic, MAGIC, 'bad magic string');
 
	var cipher = buf.readString();
	var kdf = buf.readString();
	var kdfOpts = buf.readBuffer();
 
	var nkeys = buf.readInt();
	if (nkeys !== 1) {
		throw (new Error('OpenSSH-format key file contains ' +
		    'multiple keys: this is unsupported.'));
	}
 
	var pubKey = buf.readBuffer();
 
	if (type === 'public') {
		assert.ok(buf.atEnd(), 'excess bytes left after key');
		return (rfc4253.read(pubKey));
	}
 
	var privKeyBlob = buf.readBuffer();
	assert.ok(buf.atEnd(), 'excess bytes left after key');
 
	var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts });
	switch (kdf) {
	case 'none':
		if (cipher !== 'none') {
			throw (new Error('OpenSSH-format key uses KDF "none" ' +
			     'but specifies a cipher other than "none"'));
		}
		break;
	case 'bcrypt':
		var salt = kdfOptsBuf.readBuffer();
		var rounds = kdfOptsBuf.readInt();
		var cinf = utils.opensshCipherInfo(cipher);
		if (bcrypt === undefined) {
			bcrypt = require('bcrypt-pbkdf');
		}
 
		if (typeof (options.passphrase) === 'string') {
			options.passphrase = new Buffer(options.passphrase,
			    'utf-8');
		}
		if (!Buffer.isBuffer(options.passphrase)) {
			throw (new errors.KeyEncryptedError(
			    options.filename, 'OpenSSH'));
		}
 
		var pass = new Uint8Array(options.passphrase);
		var salti = new Uint8Array(salt);
		/* Use the pbkdf to derive both the key and the IV. */
		var out = new Uint8Array(cinf.keySize + cinf.blockSize);
		var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
		    out, out.length, rounds);
		if (res !== 0) {
			throw (new Error('bcrypt_pbkdf function returned ' +
			    'failure, parameters invalid'));
		}
		out = new Buffer(out);
		var ckey = out.slice(0, cinf.keySize);
		var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
		var cipherStream = crypto.createDecipheriv(cinf.opensslName,
		    ckey, iv);
		cipherStream.setAutoPadding(false);
		var chunk, chunks = [];
		cipherStream.once('error', function (e) {
			if (e.toString().indexOf('bad decrypt') !== -1) {
				throw (new Error('Incorrect passphrase ' +
				    'supplied, could not decrypt key'));
			}
			throw (e);
		});
		cipherStream.write(privKeyBlob);
		cipherStream.end();
		while ((chunk = cipherStream.read()) !== null)
			chunks.push(chunk);
		privKeyBlob = Buffer.concat(chunks);
		break;
	default:
		throw (new Error(
		    'OpenSSH-format key uses unknown KDF "' + kdf + '"'));
	}
 
	buf = new SSHBuffer({buffer: privKeyBlob});
 
	var checkInt1 = buf.readInt();
	var checkInt2 = buf.readInt();
	if (checkInt1 !== checkInt2) {
		throw (new Error('Incorrect passphrase supplied, could not ' +
		    'decrypt key'));
	}
 
	var ret = {};
	var key = rfc4253.readInternal(ret, 'private', buf.remainder());
 
	buf.skip(ret.consumed);
 
	var comment = buf.readString();
	key.comment = comment;
 
	return (key);
}
 
function write(key, options) {
	var pubKey;
	if (PrivateKey.isPrivateKey(key))
		pubKey = key.toPublic();
	else
		pubKey = key;
 
	var cipher = 'none';
	var kdf = 'none';
	var kdfopts = new Buffer(0);
	var cinf = { blockSize: 8 };
	var passphrase;
	if (options !== undefined) {
		passphrase = options.passphrase;
		if (typeof (passphrase) === 'string')
			passphrase = new Buffer(passphrase, 'utf-8');
		if (passphrase !== undefined) {
			assert.buffer(passphrase, 'options.passphrase');
			assert.optionalString(options.cipher, 'options.cipher');
			cipher = options.cipher;
			if (cipher === undefined)
				cipher = 'aes128-ctr';
			cinf = utils.opensshCipherInfo(cipher);
			kdf = 'bcrypt';
		}
	}
 
	var privBuf;
	if (PrivateKey.isPrivateKey(key)) {
		privBuf = new SSHBuffer({});
		var checkInt = crypto.randomBytes(4).readUInt32BE(0);
		privBuf.writeInt(checkInt);
		privBuf.writeInt(checkInt);
		privBuf.write(key.toBuffer('rfc4253'));
		privBuf.writeString(key.comment || '');
 
		var n = 1;
		while (privBuf._offset % cinf.blockSize !== 0)
			privBuf.writeChar(n++);
		privBuf = privBuf.toBuffer();
	}
 
	switch (kdf) {
	case 'none':
		break;
	case 'bcrypt':
		var salt = crypto.randomBytes(16);
		var rounds = 16;
		var kdfssh = new SSHBuffer({});
		kdfssh.writeBuffer(salt);
		kdfssh.writeInt(rounds);
		kdfopts = kdfssh.toBuffer();
 
		if (bcrypt === undefined) {
			bcrypt = require('bcrypt-pbkdf');
		}
		var pass = new Uint8Array(passphrase);
		var salti = new Uint8Array(salt);
		/* Use the pbkdf to derive both the key and the IV. */
		var out = new Uint8Array(cinf.keySize + cinf.blockSize);
		var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
		    out, out.length, rounds);
		if (res !== 0) {
			throw (new Error('bcrypt_pbkdf function returned ' +
			    'failure, parameters invalid'));
		}
		out = new Buffer(out);
		var ckey = out.slice(0, cinf.keySize);
		var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
 
		var cipherStream = crypto.createCipheriv(cinf.opensslName,
		    ckey, iv);
		cipherStream.setAutoPadding(false);
		var chunk, chunks = [];
		cipherStream.once('error', function (e) {
			throw (e);
		});
		cipherStream.write(privBuf);
		cipherStream.end();
		while ((chunk = cipherStream.read()) !== null)
			chunks.push(chunk);
		privBuf = Buffer.concat(chunks);
		break;
	default:
		throw (new Error('Unsupported kdf ' + kdf));
	}
 
	var buf = new SSHBuffer({});
 
	buf.writeCString(MAGIC);
	buf.writeString(cipher);	/* cipher */
	buf.writeString(kdf);		/* kdf */
	buf.writeBuffer(kdfopts);	/* kdfoptions */
 
	buf.writeInt(1);		/* nkeys */
	buf.writeBuffer(pubKey.toBuffer('rfc4253'));
 
	if (privBuf)
		buf.writeBuffer(privBuf);
 
	buf = buf.toBuffer();
 
	var header;
	if (PrivateKey.isPrivateKey(key))
		header = 'OPENSSH PRIVATE KEY';
	else
		header = 'OPENSSH PUBLIC KEY';
 
	var tmp = buf.toString('base64');
	var len = tmp.length + (tmp.length / 70) +
	    18 + 16 + header.length*2 + 10;
	buf = new Buffer(len);
	var o = 0;
	o += buf.write('-----BEGIN ' + header + '-----\n', o);
	for (var i = 0; i < tmp.length; ) {
		var limit = i + 70;
		if (limit > tmp.length)
			limit = tmp.length;
		o += buf.write(tmp.slice(i, limit), o);
		buf[o++] = 10;
		i = limit;
	}
	o += buf.write('-----END ' + header + '-----\n', o);
 
	return (buf.slice(0, o));
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/ssh.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/ssh.js

Statements: 18.64% (11 / 59)      Branches: 0% (0 / 22)      Functions: 0% (0 / 2)      Lines: 18.64% (11 / 59)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116    1         1 1 1 1 1   1     1   1   1                                                                                                                                                         1                                    
// Copyright 2015 Joyent, Inc.
 
module.exports = {
	read: read,
	write: write
};
 
var assert = require('assert-plus');
var rfc4253 = require('./rfc4253');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
 
var sshpriv = require('./ssh-private');
 
/*JSSTYLED*/
var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([\n \t]+([^\n]+))?$/;
/*JSSTYLED*/
var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/ \t\n]+[=]*)(.*)$/;
 
function read(buf, options) {
	if (typeof (buf) !== 'string') {
		assert.buffer(buf, 'buf');
		buf = buf.toString('ascii');
	}
 
	var trimmed = buf.trim().replace(/[\\\r]/g, '');
	var m = trimmed.match(SSHKEY_RE);
	if (!m)
		m = trimmed.match(SSHKEY_RE2);
	assert.ok(m, 'key must match regex');
 
	var type = rfc4253.algToKeyType(m[1]);
	var kbuf = new Buffer(m[2], 'base64');
 
	/*
	 * This is a bit tricky. If we managed to parse the key and locate the
	 * key comment with the regex, then do a non-partial read and assert
	 * that we have consumed all bytes. If we couldn't locate the key
	 * comment, though, there may be whitespace shenanigans going on that
	 * have conjoined the comment to the rest of the key. We do a partial
	 * read in this case to try to make the best out of a sorry situation.
	 */
	var key;
	var ret = {};
	if (m[4]) {
		try {
			key = rfc4253.read(kbuf);
 
		} catch (e) {
			m = trimmed.match(SSHKEY_RE2);
			assert.ok(m, 'key must match regex');
			kbuf = new Buffer(m[2], 'base64');
			key = rfc4253.readInternal(ret, 'public', kbuf);
		}
	} else {
		key = rfc4253.readInternal(ret, 'public', kbuf);
	}
 
	assert.strictEqual(type, key.type);
 
	if (m[4] && m[4].length > 0) {
		key.comment = m[4];
 
	} else if (ret.consumed) {
		/*
		 * Now the magic: trying to recover the key comment when it's
		 * gotten conjoined to the key or otherwise shenanigan'd.
		 *
		 * Work out how much base64 we used, then drop all non-base64
		 * chars from the beginning up to this point in the the string.
		 * Then offset in this and try to make up for missing = chars.
		 */
		var data = m[2] + m[3];
		var realOffset = Math.ceil(ret.consumed / 3) * 4;
		data = data.slice(0, realOffset - 2). /*JSSTYLED*/
		    replace(/[^a-zA-Z0-9+\/=]/g, '') +
		    data.slice(realOffset - 2);
 
		var padding = ret.consumed % 3;
		if (padding > 0 &&
		    data.slice(realOffset - 1, realOffset) !== '=')
			realOffset--;
		while (data.slice(realOffset, realOffset + 1) === '=')
			realOffset++;
 
		/* Finally, grab what we think is the comment & clean it up. */
		var trailer = data.slice(realOffset);
		trailer = trailer.replace(/[\r\n]/g, ' ').
		    replace(/^\s+/, '');
		if (trailer.match(/^[a-zA-Z0-9]/))
			key.comment = trailer;
	}
 
	return (key);
}
 
function write(key, options) {
	assert.object(key);
	if (!Key.isKey(key))
		throw (new Error('Must be a public key'));
 
	var parts = [];
	var alg = rfc4253.keyTypeToAlg(key);
	parts.push(alg);
 
	var buf = rfc4253.write(key);
	parts.push(buf.toString('base64'));
 
	if (key.comment)
		parts.push(key.comment);
 
	return (new Buffer(parts.join(' ')));
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/x509-pem.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/x509-pem.js

Statements: 29.17% (14 / 48)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 29.17% (14 / 48)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79    1   1             1 1 1 1 1 1 1 1 1 1   1                                                                 1                                              
// Copyright 2016 Joyent, Inc.
 
var x509 = require('./x509');
 
module.exports = {
	read: read,
	verify: x509.verify,
	sign: x509.sign,
	write: write
};
 
var assert = require('assert-plus');
var asn1 = require('asn1');
var algs = require('../algs');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
var pem = require('./pem');
var Identity = require('../identity');
var Signature = require('../signature');
var Certificate = require('../certificate');
 
function read(buf, options) {
	if (typeof (buf) !== 'string') {
		assert.buffer(buf, 'buf');
		buf = buf.toString('ascii');
	}
 
	var lines = buf.trim().split(/[\r\n]+/g);
 
	var m = lines[0].match(/*JSSTYLED*/
	    /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);
	assert.ok(m, 'invalid PEM header');
 
	var m2 = lines[lines.length - 1].match(/*JSSTYLED*/
	    /[-]+[ ]*END CERTIFICATE[ ]*[-]+/);
	assert.ok(m2, 'invalid PEM footer');
 
	var headers = {};
	while (true) {
		lines = lines.slice(1);
		m = lines[0].match(/*JSSTYLED*/
		    /^([A-Za-z0-9-]+): (.+)$/);
		if (!m)
			break;
		headers[m[1].toLowerCase()] = m[2];
	}
 
	/* Chop off the first and last lines */
	lines = lines.slice(0, -1).join('');
	buf = new Buffer(lines, 'base64');
 
	return (x509.read(buf, options));
}
 
function write(cert, options) {
	var dbuf = x509.write(cert, options);
 
	var header = 'CERTIFICATE';
	var tmp = dbuf.toString('base64');
	var len = tmp.length + (tmp.length / 64) +
	    18 + 16 + header.length*2 + 10;
	var buf = new Buffer(len);
	var o = 0;
	o += buf.write('-----BEGIN ' + header + '-----\n', o);
	for (var i = 0; i < tmp.length; ) {
		var limit = i + 64;
		if (limit > tmp.length)
			limit = tmp.length;
		o += buf.write(tmp.slice(i, limit), o);
		buf[o++] = 10;
		i = limit;
	}
	o += buf.write('-----END ' + header + '-----\n', o);
 
	return (buf.slice(0, o));
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/x509.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/formats/x509.js

Statements: 10.81% (44 / 407)      Branches: 0% (0 / 160)      Functions: 18.18% (4 / 22)      Lines: 10.81% (44 / 407)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701    1             1 1 1 1 1 1 1 1 1 1 1             1           1                                       1 4     1 5     1                         1 11   1 1   1               1                                                                                                                                                                                                                 1                     1                         1                 1 1 5     1         1                                                                                                                                                                                                                                                                                         1   1                                       1   1                         1             1                       1                                         1                                                           1                                                                                                                                                                                                                                                                                                                                                         1                                           1                                            
// Copyright 2016 Joyent, Inc.
 
module.exports = {
	read: read,
	verify: verify,
	sign: sign,
	write: write
};
 
var assert = require('assert-plus');
var asn1 = require('asn1');
var algs = require('../algs');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
var pem = require('./pem');
var Identity = require('../identity');
var Signature = require('../signature');
var Certificate = require('../certificate');
var pkcs8 = require('./pkcs8');
 
/*
 * This file is based on RFC5280 (X.509).
 */
 
/* Helper to read in a single mpint */
function readMPInt(der, nm) {
	assert.strictEqual(der.peek(), asn1.Ber.Integer,
	    nm + ' is not an Integer');
	return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
}
 
function verify(cert, key) {
	var sig = cert.signatures.x509;
	assert.object(sig, 'x509 signature');
 
	var algParts = sig.algo.split('-');
	if (algParts[0] !== key.type)
		return (false);
 
	var blob = sig.cache;
	if (blob === undefined) {
		var der = new asn1.BerWriter();
		writeTBSCert(cert, der);
		blob = der.buffer;
	}
 
	var verifier = key.createVerify(algParts[1]);
	verifier.write(blob);
	return (verifier.verify(sig.signature));
}
 
function Local(i) {
	return (asn1.Ber.Context | asn1.Ber.Constructor | i);
}
 
function Context(i) {
	return (asn1.Ber.Context | i);
}
 
var SIGN_ALGS = {
	'rsa-md5': '1.2.840.113549.1.1.4',
	'rsa-sha1': '1.2.840.113549.1.1.5',
	'rsa-sha256': '1.2.840.113549.1.1.11',
	'rsa-sha384': '1.2.840.113549.1.1.12',
	'rsa-sha512': '1.2.840.113549.1.1.13',
	'dsa-sha1': '1.2.840.10040.4.3',
	'dsa-sha256': '2.16.840.1.101.3.4.3.2',
	'ecdsa-sha1': '1.2.840.10045.4.1',
	'ecdsa-sha256': '1.2.840.10045.4.3.2',
	'ecdsa-sha384': '1.2.840.10045.4.3.3',
	'ecdsa-sha512': '1.2.840.10045.4.3.4'
};
Object.keys(SIGN_ALGS).forEach(function (k) {
	SIGN_ALGS[SIGN_ALGS[k]] = k;
});
SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5';
SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1';
 
var EXTS = {
	'issuerKeyId': '2.5.29.35',
	'altName': '2.5.29.17',
	'basicConstraints': '2.5.29.19',
	'keyUsage': '2.5.29.15',
	'extKeyUsage': '2.5.29.37'
};
 
function read(buf, options) {
	if (typeof (buf) === 'string') {
		buf = new Buffer(buf, 'binary');
	}
	assert.buffer(buf, 'buf');
 
	var der = new asn1.BerReader(buf);
 
	der.readSequence();
	if (Math.abs(der.length - der.remain) > 1) {
		throw (new Error('DER sequence does not contain whole byte ' +
		    'stream'));
	}
 
	var tbsStart = der.offset;
	der.readSequence();
	var sigOffset = der.offset + der.length;
	var tbsEnd = sigOffset;
 
	if (der.peek() === Local(0)) {
		der.readSequence(Local(0));
		var version = der.readInt();
		assert.ok(version <= 3,
		    'only x.509 versions up to v3 supported');
	}
 
	var cert = {};
	cert.signatures = {};
	var sig = (cert.signatures.x509 = {});
	sig.extras = {};
 
	cert.serial = readMPInt(der, 'serial');
 
	der.readSequence();
	var after = der.offset + der.length;
	var certAlgOid = der.readOID();
	var certAlg = SIGN_ALGS[certAlgOid];
	if (certAlg === undefined)
		throw (new Error('unknown signature algorithm ' + certAlgOid));
 
	der._offset = after;
	cert.issuer = Identity.parseAsn1(der);
 
	der.readSequence();
	cert.validFrom = readDate(der);
	cert.validUntil = readDate(der);
 
	cert.subjects = [Identity.parseAsn1(der)];
 
	der.readSequence();
	after = der.offset + der.length;
	cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der);
	der._offset = after;
 
	/* issuerUniqueID */
	if (der.peek() === Local(1)) {
		der.readSequence(Local(1));
		sig.extras.issuerUniqueID =
		    buf.slice(der.offset, der.offset + der.length);
		der._offset += der.length;
	}
 
	/* subjectUniqueID */
	if (der.peek() === Local(2)) {
		der.readSequence(Local(2));
		sig.extras.subjectUniqueID =
		    buf.slice(der.offset, der.offset + der.length);
		der._offset += der.length;
	}
 
	/* extensions */
	if (der.peek() === Local(3)) {
		der.readSequence(Local(3));
		var extEnd = der.offset + der.length;
		der.readSequence();
 
		while (der.offset < extEnd)
			readExtension(cert, buf, der);
 
		assert.strictEqual(der.offset, extEnd);
	}
 
	assert.strictEqual(der.offset, sigOffset);
 
	der.readSequence();
	after = der.offset + der.length;
	var sigAlgOid = der.readOID();
	var sigAlg = SIGN_ALGS[sigAlgOid];
	if (sigAlg === undefined)
		throw (new Error('unknown signature algorithm ' + sigAlgOid));
	der._offset = after;
 
	var sigData = der.readString(asn1.Ber.BitString, true);
	if (sigData[0] === 0)
		sigData = sigData.slice(1);
	var algParts = sigAlg.split('-');
 
	sig.signature = Signature.parse(sigData, algParts[0], 'asn1');
	sig.signature.hashAlgorithm = algParts[1];
	sig.algo = sigAlg;
	sig.cache = buf.slice(tbsStart, tbsEnd);
 
	return (new Certificate(cert));
}
 
function readDate(der) {
	if (der.peek() === asn1.Ber.UTCTime) {
		return (utcTimeToDate(der.readString(asn1.Ber.UTCTime)));
	} else if (der.peek() === asn1.Ber.GeneralizedTime) {
		return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime)));
	} else {
		throw (new Error('Unsupported date format'));
	}
}
 
/* RFC5280, section 4.2.1.6 (GeneralName type) */
var ALTNAME = {
	OtherName: Local(0),
	RFC822Name: Context(1),
	DNSName: Context(2),
	X400Address: Local(3),
	DirectoryName: Local(4),
	EDIPartyName: Local(5),
	URI: Context(6),
	IPAddress: Context(7),
	OID: Context(8)
};
 
/* RFC5280, section 4.2.1.12 (KeyPurposeId) */
var EXTPURPOSE = {
	'serverAuth': '1.3.6.1.5.5.7.3.1',
	'clientAuth': '1.3.6.1.5.5.7.3.2',
	'codeSigning': '1.3.6.1.5.5.7.3.3',
 
	/* See https://github.com/joyent/oid-docs/blob/master/root.md */
	'joyentDocker': '1.3.6.1.4.1.38678.1.4.1',
	'joyentCmon': '1.3.6.1.4.1.38678.1.4.2'
};
var EXTPURPOSE_REV = {};
Object.keys(EXTPURPOSE).forEach(function (k) {
	EXTPURPOSE_REV[EXTPURPOSE[k]] = k;
});
 
var KEYUSEBITS = [
	'signature', 'identity', 'keyEncryption',
	'encryption', 'keyAgreement', 'ca', 'crl'
];
 
function readExtension(cert, buf, der) {
	der.readSequence();
	var after = der.offset + der.length;
	var extId = der.readOID();
	var id;
	var sig = cert.signatures.x509;
	sig.extras.exts = [];
 
	var critical;
	if (der.peek() === asn1.Ber.Boolean)
		critical = der.readBoolean();
 
	switch (extId) {
	case (EXTS.basicConstraints):
		der.readSequence(asn1.Ber.OctetString);
		der.readSequence();
		var bcEnd = der.offset + der.length;
		var ca = false;
		if (der.peek() === asn1.Ber.Boolean)
			ca = der.readBoolean();
		if (cert.purposes === undefined)
			cert.purposes = [];
		if (ca === true)
			cert.purposes.push('ca');
		var bc = { oid: extId, critical: critical };
		if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer)
			bc.pathLen = der.readInt();
		sig.extras.exts.push(bc);
		break;
	case (EXTS.extKeyUsage):
		der.readSequence(asn1.Ber.OctetString);
		der.readSequence();
		if (cert.purposes === undefined)
			cert.purposes = [];
		var ekEnd = der.offset + der.length;
		while (der.offset < ekEnd) {
			var oid = der.readOID();
			cert.purposes.push(EXTPURPOSE_REV[oid] || oid);
		}
		/*
		 * This is a bit of a hack: in the case where we have a cert
		 * that's only allowed to do serverAuth or clientAuth (and not
		 * the other), we want to make sure all our Subjects are of
		 * the right type. But we already parsed our Subjects and
		 * decided if they were hosts or users earlier (since it appears
		 * first in the cert).
		 *
		 * So we go through and mutate them into the right kind here if
		 * it doesn't match. This might not be hugely beneficial, as it
		 * seems that single-purpose certs are not often seen in the
		 * wild.
		 */
		if (cert.purposes.indexOf('serverAuth') !== -1 &&
		    cert.purposes.indexOf('clientAuth') === -1) {
			cert.subjects.forEach(function (ide) {
				if (ide.type !== 'host') {
					ide.type = 'host';
					ide.hostname = ide.uid ||
					    ide.email ||
					    ide.components[0].value;
				}
			});
		} else if (cert.purposes.indexOf('clientAuth') !== -1 &&
		    cert.purposes.indexOf('serverAuth') === -1) {
			cert.subjects.forEach(function (ide) {
				if (ide.type !== 'user') {
					ide.type = 'user';
					ide.uid = ide.hostname ||
					    ide.email ||
					    ide.components[0].value;
				}
			});
		}
		sig.extras.exts.push({ oid: extId, critical: critical });
		break;
	case (EXTS.keyUsage):
		der.readSequence(asn1.Ber.OctetString);
		var bits = der.readString(asn1.Ber.BitString, true);
		var setBits = readBitField(bits, KEYUSEBITS);
		setBits.forEach(function (bit) {
			if (cert.purposes === undefined)
				cert.purposes = [];
			if (cert.purposes.indexOf(bit) === -1)
				cert.purposes.push(bit);
		});
		sig.extras.exts.push({ oid: extId, critical: critical,
		    bits: bits });
		break;
	case (EXTS.altName):
		der.readSequence(asn1.Ber.OctetString);
		der.readSequence();
		var aeEnd = der.offset + der.length;
		while (der.offset < aeEnd) {
			switch (der.peek()) {
			case ALTNAME.OtherName:
			case ALTNAME.EDIPartyName:
				der.readSequence();
				der._offset += der.length;
				break;
			case ALTNAME.OID:
				der.readOID(ALTNAME.OID);
				break;
			case ALTNAME.RFC822Name:
				/* RFC822 specifies email addresses */
				var email = der.readString(ALTNAME.RFC822Name);
				id = Identity.forEmail(email);
				if (!cert.subjects[0].equals(id))
					cert.subjects.push(id);
				break;
			case ALTNAME.DirectoryName:
				der.readSequence(ALTNAME.DirectoryName);
				id = Identity.parseAsn1(der);
				if (!cert.subjects[0].equals(id))
					cert.subjects.push(id);
				break;
			case ALTNAME.DNSName:
				var host = der.readString(
				    ALTNAME.DNSName);
				id = Identity.forHost(host);
				if (!cert.subjects[0].equals(id))
					cert.subjects.push(id);
				break;
			default:
				der.readString(der.peek());
				break;
			}
		}
		sig.extras.exts.push({ oid: extId, critical: critical });
		break;
	default:
		sig.extras.exts.push({
			oid: extId,
			critical: critical,
			data: der.readString(asn1.Ber.OctetString, true)
		});
		break;
	}
 
	der._offset = after;
}
 
var UTCTIME_RE =
    /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
function utcTimeToDate(t) {
	var m = t.match(UTCTIME_RE);
	assert.ok(m, 'timestamps must be in UTC');
	var d = new Date();
 
	var thisYear = d.getUTCFullYear();
	var century = Math.floor(thisYear / 100) * 100;
 
	var year = parseInt(m[1], 10);
	if (thisYear % 100 < 50 && year >= 60)
		year += (century - 1);
	else
		year += century;
	d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10));
	d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
	if (m[6] && m[6].length > 0)
		d.setUTCSeconds(parseInt(m[6], 10));
	return (d);
}
 
var GTIME_RE =
    /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
function gTimeToDate(t) {
	var m = t.match(GTIME_RE);
	assert.ok(m);
	var d = new Date();
 
	d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1,
	    parseInt(m[3], 10));
	d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
	if (m[6] && m[6].length > 0)
		d.setUTCSeconds(parseInt(m[6], 10));
	return (d);
}
 
function zeroPad(n) {
	var s = '' + n;
	while (s.length < 2)
		s = '0' + s;
	return (s);
}
 
function dateToUTCTime(d) {
	var s = '';
	s += zeroPad(d.getUTCFullYear() % 100);
	s += zeroPad(d.getUTCMonth() + 1);
	s += zeroPad(d.getUTCDate());
	s += zeroPad(d.getUTCHours());
	s += zeroPad(d.getUTCMinutes());
	s += zeroPad(d.getUTCSeconds());
	s += 'Z';
	return (s);
}
 
function sign(cert, key) {
	if (cert.signatures.x509 === undefined)
		cert.signatures.x509 = {};
	var sig = cert.signatures.x509;
 
	sig.algo = key.type + '-' + key.defaultHashAlgorithm();
	if (SIGN_ALGS[sig.algo] === undefined)
		return (false);
 
	var der = new asn1.BerWriter();
	writeTBSCert(cert, der);
	var blob = der.buffer;
	sig.cache = blob;
 
	var signer = key.createSign();
	signer.write(blob);
	cert.signatures.x509.signature = signer.sign();
 
	return (true);
}
 
function write(cert, options) {
	var sig = cert.signatures.x509;
	assert.object(sig, 'x509 signature');
 
	var der = new asn1.BerWriter();
	der.startSequence();
	if (sig.cache) {
		der._ensure(sig.cache.length);
		sig.cache.copy(der._buf, der._offset);
		der._offset += sig.cache.length;
	} else {
		writeTBSCert(cert, der);
	}
 
	der.startSequence();
	der.writeOID(SIGN_ALGS[sig.algo]);
	if (sig.algo.match(/^rsa-/))
		der.writeNull();
	der.endSequence();
 
	var sigData = sig.signature.toBuffer('asn1');
	var data = new Buffer(sigData.length + 1);
	data[0] = 0;
	sigData.copy(data, 1);
	der.writeBuffer(data, asn1.Ber.BitString);
	der.endSequence();
 
	return (der.buffer);
}
 
function writeTBSCert(cert, der) {
	var sig = cert.signatures.x509;
	assert.object(sig, 'x509 signature');
 
	der.startSequence();
 
	der.startSequence(Local(0));
	der.writeInt(2);
	der.endSequence();
 
	der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer);
 
	der.startSequence();
	der.writeOID(SIGN_ALGS[sig.algo]);
	der.endSequence();
 
	cert.issuer.toAsn1(der);
 
	der.startSequence();
	der.writeString(dateToUTCTime(cert.validFrom), asn1.Ber.UTCTime);
	der.writeString(dateToUTCTime(cert.validUntil), asn1.Ber.UTCTime);
	der.endSequence();
 
	var subject = cert.subjects[0];
	var altNames = cert.subjects.slice(1);
	subject.toAsn1(der);
 
	pkcs8.writePkcs8(der, cert.subjectKey);
 
	if (sig.extras && sig.extras.issuerUniqueID) {
		der.writeBuffer(sig.extras.issuerUniqueID, Local(1));
	}
 
	if (sig.extras && sig.extras.subjectUniqueID) {
		der.writeBuffer(sig.extras.subjectUniqueID, Local(2));
	}
 
	if (altNames.length > 0 || subject.type === 'host' ||
	    (cert.purposes !== undefined && cert.purposes.length > 0) ||
	    (sig.extras && sig.extras.exts)) {
		der.startSequence(Local(3));
		der.startSequence();
 
		var exts = [];
		if (cert.purposes !== undefined && cert.purposes.length > 0) {
			exts.push({
				oid: EXTS.basicConstraints,
				critical: true
			});
			exts.push({
				oid: EXTS.keyUsage,
				critical: true
			});
			exts.push({
				oid: EXTS.extKeyUsage,
				critical: true
			});
		}
		exts.push({ oid: EXTS.altName });
		if (sig.extras && sig.extras.exts)
			exts = sig.extras.exts;
 
		for (var i = 0; i < exts.length; ++i) {
			der.startSequence();
			der.writeOID(exts[i].oid);
 
			if (exts[i].critical !== undefined)
				der.writeBoolean(exts[i].critical);
 
			if (exts[i].oid === EXTS.altName) {
				der.startSequence(asn1.Ber.OctetString);
				der.startSequence();
				if (subject.type === 'host') {
					der.writeString(subject.hostname,
					    Context(2));
				}
				for (var j = 0; j < altNames.length; ++j) {
					if (altNames[j].type === 'host') {
						der.writeString(
						    altNames[j].hostname,
						    ALTNAME.DNSName);
					} else if (altNames[j].type ===
					    'email') {
						der.writeString(
						    altNames[j].email,
						    ALTNAME.RFC822Name);
					} else {
						/*
						 * Encode anything else as a
						 * DN style name for now.
						 */
						der.startSequence(
						    ALTNAME.DirectoryName);
						altNames[j].toAsn1(der);
						der.endSequence();
					}
				}
				der.endSequence();
				der.endSequence();
			} else if (exts[i].oid === EXTS.basicConstraints) {
				der.startSequence(asn1.Ber.OctetString);
				der.startSequence();
				var ca = (cert.purposes.indexOf('ca') !== -1);
				var pathLen = exts[i].pathLen;
				der.writeBoolean(ca);
				if (pathLen !== undefined)
					der.writeInt(pathLen);
				der.endSequence();
				der.endSequence();
			} else if (exts[i].oid === EXTS.extKeyUsage) {
				der.startSequence(asn1.Ber.OctetString);
				der.startSequence();
				cert.purposes.forEach(function (purpose) {
					if (purpose === 'ca')
						return;
					if (KEYUSEBITS.indexOf(purpose) !== -1)
						return;
					var oid = purpose;
					if (EXTPURPOSE[purpose] !== undefined)
						oid = EXTPURPOSE[purpose];
					der.writeOID(oid);
				});
				der.endSequence();
				der.endSequence();
			} else if (exts[i].oid === EXTS.keyUsage) {
				der.startSequence(asn1.Ber.OctetString);
				/*
				 * If we parsed this certificate from a byte
				 * stream (i.e. we didn't generate it in sshpk)
				 * then we'll have a ".bits" property on the
				 * ext with the original raw byte contents.
				 *
				 * If we have this, use it here instead of
				 * regenerating it. This guarantees we output
				 * the same data we parsed, so signatures still
				 * validate.
				 */
				if (exts[i].bits !== undefined) {
					der.writeBuffer(exts[i].bits,
					    asn1.Ber.BitString);
				} else {
					var bits = writeBitField(cert.purposes,
					    KEYUSEBITS);
					der.writeBuffer(bits,
					    asn1.Ber.BitString);
				}
				der.endSequence();
			} else {
				der.writeBuffer(exts[i].data,
				    asn1.Ber.OctetString);
			}
 
			der.endSequence();
		}
 
		der.endSequence();
		der.endSequence();
	}
 
	der.endSequence();
}
 
/*
 * Reads an ASN.1 BER bitfield out of the Buffer produced by doing
 * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw
 * contents of the BitString tag, which is a count of unused bits followed by
 * the bits as a right-padded byte string.
 *
 * `bits` is the Buffer, `bitIndex` should contain an array of string names
 * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec.
 *
 * Returns an array of Strings, the names of the bits that were set to 1.
 */
function readBitField(bits, bitIndex) {
	var bitLen = 8 * (bits.length - 1) - bits[0];
	var setBits = {};
	for (var i = 0; i < bitLen; ++i) {
		var byteN = 1 + Math.floor(i / 8);
		var bit = 7 - (i % 8);
		var mask = 1 << bit;
		var bitVal = ((bits[byteN] & mask) !== 0);
		var name = bitIndex[i];
		if (bitVal && typeof (name) === 'string') {
			setBits[name] = true;
		}
	}
	return (Object.keys(setBits));
}
 
/*
 * `setBits` is an array of strings, containing the names for each bit that
 * sould be set to 1. `bitIndex` is same as in `readBitField()`.
 *
 * Returns a Buffer, ready to be written out with `BerWriter#writeString()`.
 */
function writeBitField(setBits, bitIndex) {
	var bitLen = bitIndex.length;
	var blen = Math.ceil(bitLen / 8);
	var unused = blen * 8 - bitLen;
	var bits = new Buffer(1 + blen);
	bits.fill(0);
	bits[0] = unused;
	for (var i = 0; i < bitLen; ++i) {
		var byteN = 1 + Math.floor(i / 8);
		var bit = 7 - (i % 8);
		var mask = 1 << bit;
		var name = bitIndex[i];
		if (name === undefined)
			continue;
		var bitVal = (setBits.indexOf(name) !== -1);
		if (bitVal) {
			bits[byteN] |= mask;
		}
	}
	return (bits);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/
File Statements Branches Functions Lines
index.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/index.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22          1           1                    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
// If you have no idea what ASN.1 or BER is, see this:
// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
 
var Ber = require('./ber/index');
 
 
 
///--- Exported API
 
module.exports = {
 
  Ber: Ber,
 
  BerReader: Ber.Reader,
 
  BerWriter: Ber.Writer
 
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/

Statements: 16.57% (57 / 344)      Branches: 1.31% (2 / 153)      Functions: 0% (0 / 38)      Lines: 16.57% (57 / 344)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/
File Statements Branches Functions Lines
errors.js 20% (1 / 5) 0% (0 / 2) 0% (0 / 1) 20% (1 / 5)
index.js 100% (11 / 11) 50% (2 / 4) 100% (0 / 0) 100% (11 / 11)
reader.js 15.63% (20 / 128) 0% (0 / 68) 0% (0 / 15) 15.63% (20 / 128)
types.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
writer.js 12.06% (24 / 199) 0% (0 / 79) 0% (0 / 22) 12.06% (24 / 199)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/errors.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/errors.js

Statements: 20% (1 / 5)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 20% (1 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15      1                      
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
 
module.exports = {
 
  newInvalidAsn1Error: function(msg) {
    var e = new Error();
    e.name = 'InvalidAsn1Error';
    e.message = msg || '';
    return e;
  }
 
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/index.js

Statements: 100% (11 / 11)      Branches: 50% (2 / 4)      Functions: 100% (0 / 0)      Lines: 100% (11 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29    1 1   1 1         1               1 31 31   1 1 1      
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
var errors = require('./errors');
var types = require('./types');
 
var Reader = require('./reader');
var Writer = require('./writer');
 
 
///--- Exports
 
module.exports = {
 
  Reader: Reader,
 
  Writer: Writer
 
};
 
for (var t in types) {
  Eif (types.hasOwnProperty(t))
    module.exports[t] = types[t];
}
for (var e in errors) {
  Eif (errors.hasOwnProperty(e))
    module.exports[e] = errors[e];
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/reader.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/reader.js

Statements: 15.63% (20 / 128)      Branches: 0% (0 / 68)      Functions: 0% (0 / 15)      Lines: 15.63% (20 / 128)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263    1   1 1         1           1                       1         1         1       1                       1                         1                               1                                                                                     1                                 1         1         1         1                                                             1                                                           1                                                                                 1    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
var assert = require('assert');
 
var ASN1 = require('./types');
var errors = require('./errors');
 
 
///--- Globals
 
var newInvalidAsn1Error = errors.newInvalidAsn1Error;
 
 
 
///--- API
 
function Reader(data) {
  if (!data || !Buffer.isBuffer(data))
    throw new TypeError('data must be a node Buffer');
 
  this._buf = data;
  this._size = data.length;
 
  // These hold the "current" state
  this._len = 0;
  this._offset = 0;
}
 
Object.defineProperty(Reader.prototype, 'length', {
  enumerable: true,
  get: function () { return (this._len); }
});
 
Object.defineProperty(Reader.prototype, 'offset', {
  enumerable: true,
  get: function () { return (this._offset); }
});
 
Object.defineProperty(Reader.prototype, 'remain', {
  get: function () { return (this._size - this._offset); }
});
 
Object.defineProperty(Reader.prototype, 'buffer', {
  get: function () { return (this._buf.slice(this._offset)); }
});
 
 
/**
 * Reads a single byte and advances offset; you can pass in `true` to make this
 * a "peek" operation (i.e., get the byte, but don't advance the offset).
 *
 * @param {Boolean} peek true means don't move offset.
 * @return {Number} the next byte, null if not enough data.
 */
Reader.prototype.readByte = function(peek) {
  if (this._size - this._offset < 1)
    return null;
 
  var b = this._buf[this._offset] & 0xff;
 
  if (!peek)
    this._offset += 1;
 
  return b;
};
 
 
Reader.prototype.peek = function() {
  return this.readByte(true);
};
 
 
/**
 * Reads a (potentially) variable length off the BER buffer.  This call is
 * not really meant to be called directly, as callers have to manipulate
 * the internal buffer afterwards.
 *
 * As a result of this call, you can call `Reader.length`, until the
 * next thing called that does a readLength.
 *
 * @return {Number} the amount of offset to advance the buffer.
 * @throws {InvalidAsn1Error} on bad ASN.1
 */
Reader.prototype.readLength = function(offset) {
  if (offset === undefined)
    offset = this._offset;
 
  if (offset >= this._size)
    return null;
 
  var lenB = this._buf[offset++] & 0xff;
  if (lenB === null)
    return null;
 
  if ((lenB & 0x80) == 0x80) {
    lenB &= 0x7f;
 
    if (lenB == 0)
      throw newInvalidAsn1Error('Indefinite length not supported');
 
    if (lenB > 4)
      throw newInvalidAsn1Error('encoding too long');
 
    if (this._size - offset < lenB)
      return null;
 
    this._len = 0;
    for (var i = 0; i < lenB; i++)
      this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
 
  } else {
    // Wasn't a variable length
    this._len = lenB;
  }
 
  return offset;
};
 
 
/**
 * Parses the next sequence in this BER buffer.
 *
 * To get the length of the sequence, call `Reader.length`.
 *
 * @return {Number} the sequence's tag.
 */
Reader.prototype.readSequence = function(tag) {
  var seq = this.peek();
  if (seq === null)
    return null;
  if (tag !== undefined && tag !== seq)
    throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                              ': got 0x' + seq.toString(16));
 
  var o = this.readLength(this._offset + 1); // stored in `length`
  if (o === null)
    return null;
 
  this._offset = o;
  return seq;
};
 
 
Reader.prototype.readInt = function() {
  return this._readTag(ASN1.Integer);
};
 
 
Reader.prototype.readBoolean = function() {
  return (this._readTag(ASN1.Boolean) === 0 ? false : true);
};
 
 
Reader.prototype.readEnumeration = function() {
  return this._readTag(ASN1.Enumeration);
};
 
 
Reader.prototype.readString = function(tag, retbuf) {
  if (!tag)
    tag = ASN1.OctetString;
 
  var b = this.peek();
  if (b === null)
    return null;
 
  if (b !== tag)
    throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                              ': got 0x' + b.toString(16));
 
  var o = this.readLength(this._offset + 1); // stored in `length`
 
  if (o === null)
    return null;
 
  if (this.length > this._size - o)
    return null;
 
  this._offset = o;
 
  if (this.length === 0)
    return retbuf ? new Buffer(0) : '';
 
  var str = this._buf.slice(this._offset, this._offset + this.length);
  this._offset += this.length;
 
  return retbuf ? str : str.toString('utf8');
};
 
Reader.prototype.readOID = function(tag) {
  if (!tag)
    tag = ASN1.OID;
 
  var b = this.readString(tag, true);
  if (b === null)
    return null;
 
  var values = [];
  var value = 0;
 
  for (var i = 0; i < b.length; i++) {
    var byte = b[i] & 0xff;
 
    value <<= 7;
    value += byte & 0x7f;
    if ((byte & 0x80) == 0) {
      values.push(value);
      value = 0;
    }
  }
 
  value = values.shift();
  values.unshift(value % 40);
  values.unshift((value / 40) >> 0);
 
  return values.join('.');
};
 
 
Reader.prototype._readTag = function(tag) {
  assert.ok(tag !== undefined);
 
  var b = this.peek();
 
  if (b === null)
    return null;
 
  if (b !== tag)
    throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                              ': got 0x' + b.toString(16));
 
  var o = this.readLength(this._offset + 1); // stored in `length`
  if (o === null)
    return null;
 
  if (this.length > 4)
    throw newInvalidAsn1Error('Integer too long: ' + this.length);
 
  if (this.length > this._size - o)
    return null;
  this._offset = o;
 
  var fb = this._buf[this._offset];
  var value = 0;
 
  for (var i = 0; i < this.length; i++) {
    value <<= 8;
    value |= (this._buf[this._offset++] & 0xff);
  }
 
  if ((fb & 0x80) == 0x80 && i !== 4)
    value -= (1 << (i * 8));
 
  return value >> 0;
};
 
 
 
///--- Exported API
 
module.exports = Reader;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/types.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/types.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38      1                                                                    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
 
module.exports = {
  EOC: 0,
  Boolean: 1,
  Integer: 2,
  BitString: 3,
  OctetString: 4,
  Null: 5,
  OID: 6,
  ObjectDescriptor: 7,
  External: 8,
  Real: 9, // float
  Enumeration: 10,
  PDV: 11,
  Utf8String: 12,
  RelativeOID: 13,
  Sequence: 16,
  Set: 17,
  NumericString: 18,
  PrintableString: 19,
  T61String: 20,
  VideotexString: 21,
  IA5String: 22,
  UTCTime: 23,
  GeneralizedTime: 24,
  GraphicString: 25,
  VisibleString: 26,
  GeneralString: 28,
  UniversalString: 29,
  CharacterString: 30,
  BMPString: 31,
  Constructor: 32,
  Context: 128
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/asn1/lib/ber/writer.js

Statements: 12.06% (24 / 199)      Branches: 0% (0 / 79)      Functions: 0% (0 / 22)      Lines: 12.06% (24 / 199)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318    1 1 1         1   1               1                                           1                         1                 1                 1                                                         1           1                   1                         1                                 1                           1                     1                 1                                                                                 1                                                 1                     1                                                       1                 1                                       1    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
var assert = require('assert');
var ASN1 = require('./types');
var errors = require('./errors');
 
 
///--- Globals
 
var newInvalidAsn1Error = errors.newInvalidAsn1Error;
 
var DEFAULT_OPTS = {
  size: 1024,
  growthFactor: 8
};
 
 
///--- Helpers
 
function merge(from, to) {
  assert.ok(from);
  assert.equal(typeof(from), 'object');
  assert.ok(to);
  assert.equal(typeof(to), 'object');
 
  var keys = Object.getOwnPropertyNames(from);
  keys.forEach(function(key) {
    if (to[key])
      return;
 
    var value = Object.getOwnPropertyDescriptor(from, key);
    Object.defineProperty(to, key, value);
  });
 
  return to;
}
 
 
 
///--- API
 
function Writer(options) {
  options = merge(DEFAULT_OPTS, options || {});
 
  this._buf = new Buffer(options.size || 1024);
  this._size = this._buf.length;
  this._offset = 0;
  this._options = options;
 
  // A list of offsets in the buffer where we need to insert
  // sequence tag/len pairs.
  this._seq = [];
}
 
Object.defineProperty(Writer.prototype, 'buffer', {
  get: function () {
    if (this._seq.length)
      throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)');
 
    return (this._buf.slice(0, this._offset));
  }
});
 
Writer.prototype.writeByte = function(b) {
  if (typeof(b) !== 'number')
    throw new TypeError('argument must be a Number');
 
  this._ensure(1);
  this._buf[this._offset++] = b;
};
 
 
Writer.prototype.writeInt = function(i, tag) {
  if (typeof(i) !== 'number')
    throw new TypeError('argument must be a Number');
  if (typeof(tag) !== 'number')
    tag = ASN1.Integer;
 
  var sz = 4;
 
  while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
         (sz > 1)) {
    sz--;
    i <<= 8;
  }
 
  if (sz > 4)
    throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff');
 
  this._ensure(2 + sz);
  this._buf[this._offset++] = tag;
  this._buf[this._offset++] = sz;
 
  while (sz-- > 0) {
    this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
    i <<= 8;
  }
 
};
 
 
Writer.prototype.writeNull = function() {
  this.writeByte(ASN1.Null);
  this.writeByte(0x00);
};
 
 
Writer.prototype.writeEnumeration = function(i, tag) {
  if (typeof(i) !== 'number')
    throw new TypeError('argument must be a Number');
  if (typeof(tag) !== 'number')
    tag = ASN1.Enumeration;
 
  return this.writeInt(i, tag);
};
 
 
Writer.prototype.writeBoolean = function(b, tag) {
  if (typeof(b) !== 'boolean')
    throw new TypeError('argument must be a Boolean');
  if (typeof(tag) !== 'number')
    tag = ASN1.Boolean;
 
  this._ensure(3);
  this._buf[this._offset++] = tag;
  this._buf[this._offset++] = 0x01;
  this._buf[this._offset++] = b ? 0xff : 0x00;
};
 
 
Writer.prototype.writeString = function(s, tag) {
  if (typeof(s) !== 'string')
    throw new TypeError('argument must be a string (was: ' + typeof(s) + ')');
  if (typeof(tag) !== 'number')
    tag = ASN1.OctetString;
 
  var len = Buffer.byteLength(s);
  this.writeByte(tag);
  this.writeLength(len);
  if (len) {
    this._ensure(len);
    this._buf.write(s, this._offset);
    this._offset += len;
  }
};
 
 
Writer.prototype.writeBuffer = function(buf, tag) {
  if (typeof(tag) !== 'number')
    throw new TypeError('tag must be a number');
  if (!Buffer.isBuffer(buf))
    throw new TypeError('argument must be a buffer');
 
  this.writeByte(tag);
  this.writeLength(buf.length);
  this._ensure(buf.length);
  buf.copy(this._buf, this._offset, 0, buf.length);
  this._offset += buf.length;
};
 
 
Writer.prototype.writeStringArray = function(strings) {
  if ((!strings instanceof Array))
    throw new TypeError('argument must be an Array[String]');
 
  var self = this;
  strings.forEach(function(s) {
    self.writeString(s);
  });
};
 
// This is really to solve DER cases, but whatever for now
Writer.prototype.writeOID = function(s, tag) {
  if (typeof(s) !== 'string')
    throw new TypeError('argument must be a string');
  if (typeof(tag) !== 'number')
    tag = ASN1.OID;
 
  if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
    throw new Error('argument is not a valid OID string');
 
  function encodeOctet(bytes, octet) {
    if (octet < 128) {
        bytes.push(octet);
    } else if (octet < 16384) {
        bytes.push((octet >>> 7) | 0x80);
        bytes.push(octet & 0x7F);
    } else if (octet < 2097152) {
      bytes.push((octet >>> 14) | 0x80);
      bytes.push(((octet >>> 7) | 0x80) & 0xFF);
      bytes.push(octet & 0x7F);
    } else if (octet < 268435456) {
      bytes.push((octet >>> 21) | 0x80);
      bytes.push(((octet >>> 14) | 0x80) & 0xFF);
      bytes.push(((octet >>> 7) | 0x80) & 0xFF);
      bytes.push(octet & 0x7F);
    } else {
      bytes.push(((octet >>> 28) | 0x80) & 0xFF);
      bytes.push(((octet >>> 21) | 0x80) & 0xFF);
      bytes.push(((octet >>> 14) | 0x80) & 0xFF);
      bytes.push(((octet >>> 7) | 0x80) & 0xFF);
      bytes.push(octet & 0x7F);
    }
  }
 
  var tmp = s.split('.');
  var bytes = [];
  bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
  tmp.slice(2).forEach(function(b) {
    encodeOctet(bytes, parseInt(b, 10));
  });
 
  var self = this;
  this._ensure(2 + bytes.length);
  this.writeByte(tag);
  this.writeLength(bytes.length);
  bytes.forEach(function(b) {
    self.writeByte(b);
  });
};
 
 
Writer.prototype.writeLength = function(len) {
  if (typeof(len) !== 'number')
    throw new TypeError('argument must be a Number');
 
  this._ensure(4);
 
  if (len <= 0x7f) {
    this._buf[this._offset++] = len;
  } else if (len <= 0xff) {
    this._buf[this._offset++] = 0x81;
    this._buf[this._offset++] = len;
  } else if (len <= 0xffff) {
    this._buf[this._offset++] = 0x82;
    this._buf[this._offset++] = len >> 8;
    this._buf[this._offset++] = len;
  } else if (len <= 0xffffff) {
    this._buf[this._offset++] = 0x83;
    this._buf[this._offset++] = len >> 16;
    this._buf[this._offset++] = len >> 8;
    this._buf[this._offset++] = len;
  } else {
    throw new InvalidAsn1ERror('Length too long (> 4 bytes)');
  }
};
 
Writer.prototype.startSequence = function(tag) {
  if (typeof(tag) !== 'number')
    tag = ASN1.Sequence | ASN1.Constructor;
 
  this.writeByte(tag);
  this._seq.push(this._offset);
  this._ensure(3);
  this._offset += 3;
};
 
 
Writer.prototype.endSequence = function() {
  var seq = this._seq.pop();
  var start = seq + 3;
  var len = this._offset - start;
 
  if (len <= 0x7f) {
    this._shift(start, len, -2);
    this._buf[seq] = len;
  } else if (len <= 0xff) {
    this._shift(start, len, -1);
    this._buf[seq] = 0x81;
    this._buf[seq + 1] = len;
  } else if (len <= 0xffff) {
    this._buf[seq] = 0x82;
    this._buf[seq + 1] = len >> 8;
    this._buf[seq + 2] = len;
  } else if (len <= 0xffffff) {
    this._shift(start, len, 1);
    this._buf[seq] = 0x83;
    this._buf[seq + 1] = len >> 16;
    this._buf[seq + 2] = len >> 8;
    this._buf[seq + 3] = len;
  } else {
    throw new InvalidAsn1Error('Sequence too long');
  }
};
 
 
Writer.prototype._shift = function(start, len, shift) {
  assert.ok(start !== undefined);
  assert.ok(len !== undefined);
  assert.ok(shift);
 
  this._buf.copy(this._buf, start + shift, start, start + len);
  this._offset += shift;
};
 
Writer.prototype._ensure = function(len) {
  assert.ok(len);
 
  if (this._size - this._offset < len) {
    var sz = this._size * this._options.growthFactor;
    if (sz - this._offset < len)
      sz += len;
 
    var buf = new Buffer(sz);
 
    this._buf.copy(buf, 0, 0, this._offset);
    this._buf = buf;
    this._size = sz;
  }
};
 
 
 
///--- Exported API
 
module.exports = Writer;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/

Statements: 48.91% (45 / 92)      Branches: 16.33% (8 / 49)      Functions: 25.93% (7 / 27)      Lines: 48.91% (45 / 92)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/
File Statements Branches Functions Lines
assert.js 48.91% (45 / 92) 16.33% (8 / 49) 25.93% (7 / 27) 48.91% (45 / 92)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/assert.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/node_modules/assert-plus/assert.js

Statements: 48.91% (45 / 92)      Branches: 16.33% (8 / 49)      Functions: 25.93% (7 / 27)      Lines: 48.91% (45 / 92)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213      1 1 1           1         1 36     1                   1       1             1                                                                                                               1 1 1     1     1               1 12       12 12               1 12 12       12 12                     1 12 12       12 12 12                           1 12 12       12 12 12                                 1 14 1 1   13       13       1   1     1    
// Copyright (c) 2012, Mark Cavage. All rights reserved.
// Copyright 2015 Joyent, Inc.
 
var assert = require('assert');
var Stream = require('stream').Stream;
var util = require('util');
 
 
///--- Globals
 
/* JSSTYLED */
var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
 
 
///--- Internal
 
function _capitalize(str) {
    return (str.charAt(0).toUpperCase() + str.slice(1));
}
 
function _toss(name, expected, oper, arg, actual) {
    throw new assert.AssertionError({
        message: util.format('%s (%s) is required', name, expected),
        actual: (actual === undefined) ? typeof (arg) : actual(arg),
        expected: expected,
        operator: oper || '===',
        stackStartFunction: _toss.caller
    });
}
 
function _getClass(arg) {
    return (Object.prototype.toString.call(arg).slice(8, -1));
}
 
function noop() {
    // Why even bother with asserts?
}
 
 
///--- Exports
 
var types = {
    bool: {
        check: function (arg) { return typeof (arg) === 'boolean'; }
    },
    func: {
        check: function (arg) { return typeof (arg) === 'function'; }
    },
    string: {
        check: function (arg) { return typeof (arg) === 'string'; }
    },
    object: {
        check: function (arg) {
            return typeof (arg) === 'object' && arg !== null;
        }
    },
    number: {
        check: function (arg) {
            return typeof (arg) === 'number' && !isNaN(arg);
        }
    },
    finite: {
        check: function (arg) {
            return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
        }
    },
    buffer: {
        check: function (arg) { return Buffer.isBuffer(arg); },
        operator: 'Buffer.isBuffer'
    },
    array: {
        check: function (arg) { return Array.isArray(arg); },
        operator: 'Array.isArray'
    },
    stream: {
        check: function (arg) { return arg instanceof Stream; },
        operator: 'instanceof',
        actual: _getClass
    },
    date: {
        check: function (arg) { return arg instanceof Date; },
        operator: 'instanceof',
        actual: _getClass
    },
    regexp: {
        check: function (arg) { return arg instanceof RegExp; },
        operator: 'instanceof',
        actual: _getClass
    },
    uuid: {
        check: function (arg) {
            return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
        },
        operator: 'isUUID'
    }
};
 
function _setExports(ndebug) {
    var keys = Object.keys(types);
    var out;
 
    /* re-export standard assert */
    Iif (process.env.NODE_NDEBUG) {
        out = noop;
    } else {
        out = function (arg, msg) {
            if (!arg) {
                _toss(msg, 'true', arg);
            }
        };
    }
 
    /* standard checks */
    keys.forEach(function (k) {
        Iif (ndebug) {
            out[k] = noop;
            return;
        }
        var type = types[k];
        out[k] = function (arg, msg) {
            if (!type.check(arg)) {
                _toss(msg, k, type.operator, arg, type.actual);
            }
        };
    });
 
    /* optional checks */
    keys.forEach(function (k) {
        var name = 'optional' + _capitalize(k);
        Iif (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        out[name] = function (arg, msg) {
            if (arg === undefined || arg === null) {
                return;
            }
            if (!type.check(arg)) {
                _toss(msg, k, type.operator, arg, type.actual);
            }
        };
    });
 
    /* arrayOf checks */
    keys.forEach(function (k) {
        var name = 'arrayOf' + _capitalize(k);
        Iif (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        var expected = '[' + k + ']';
        out[name] = function (arg, msg) {
            if (!Array.isArray(arg)) {
                _toss(msg, expected, type.operator, arg, type.actual);
            }
            var i;
            for (i = 0; i < arg.length; i++) {
                if (!type.check(arg[i])) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
            }
        };
    });
 
    /* optionalArrayOf checks */
    keys.forEach(function (k) {
        var name = 'optionalArrayOf' + _capitalize(k);
        Iif (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        var expected = '[' + k + ']';
        out[name] = function (arg, msg) {
            if (arg === undefined || arg === null) {
                return;
            }
            if (!Array.isArray(arg)) {
                _toss(msg, expected, type.operator, arg, type.actual);
            }
            var i;
            for (i = 0; i < arg.length; i++) {
                if (!type.check(arg[i])) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
            }
        };
    });
 
    /* re-export built-in assertions */
    Object.keys(assert).forEach(function (k) {
        if (k === 'AssertionError') {
            out[k] = assert[k];
            return;
        }
        Iif (ndebug) {
            out[k] = noop;
            return;
        }
        out[k] = assert[k];
    });
 
    /* export ourselves (for unit tests _only_) */
    out._setExports = _setExports;
 
    return out;
}
 
module.exports = _setExports(process.env.NODE_NDEBUG);
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/is-typedarray/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/is-typedarray/

Statements: 72.73% (8 / 11)      Branches: 0% (0 / 11)      Functions: 0% (0 / 3)      Lines: 72.73% (8 / 11)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/is-typedarray/
File Statements Branches Functions Lines
index.js 72.73% (8 / 11) 0% (0 / 11) 0% (0 / 3) 72.73% (8 / 11)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/is-typedarray/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/is-typedarray/index.js

Statements: 72.73% (8 / 11)      Branches: 0% (0 / 11)      Functions: 0% (0 / 3)      Lines: 72.73% (8 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 431 1 1   1 1                       1             1                           1        
module.exports      = isTypedArray
isTypedArray.strict = isStrictTypedArray
isTypedArray.loose  = isLooseTypedArray
 
var toString = Object.prototype.toString
var names = {
    '[object Int8Array]': true
  , '[object Int16Array]': true
  , '[object Int32Array]': true
  , '[object Uint8Array]': true
  , '[object Uint8ClampedArray]': true
  , '[object Uint16Array]': true
  , '[object Uint32Array]': true
  , '[object Float32Array]': true
  , '[object Float64Array]': true
}
 
function isTypedArray(arr) {
  return (
       isStrictTypedArray(arr)
    || isLooseTypedArray(arr)
  )
}
 
function isStrictTypedArray(arr) {
  return (
       arr instanceof Int8Array
    || arr instanceof Int16Array
    || arr instanceof Int32Array
    || arr instanceof Uint8Array
    || arr instanceof Uint8ClampedArray
    || arr instanceof Uint16Array
    || arr instanceof Uint32Array
    || arr instanceof Float32Array
    || arr instanceof Float64Array
  )
}
 
function isLooseTypedArray(arr) {
  return names[toString.call(arr)]
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/isstream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/isstream/

Statements: 69.23% (9 / 13)      Branches: 0% (0 / 8)      Functions: 0% (0 / 4)      Lines: 69.23% (9 / 13)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/isstream/
File Statements Branches Functions Lines
isstream.js 69.23% (9 / 13) 0% (0 / 8) 0% (0 / 4) 69.23% (9 / 13)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/isstream/isstream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/isstream/isstream.js

Statements: 69.23% (9 / 13)      Branches: 0% (0 / 8)      Functions: 0% (0 / 4)      Lines: 69.23% (9 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 291     1         1         1         1         1 1 1 1    
var stream = require('stream')
 
 
function isStream (obj) {
  return obj instanceof stream.Stream
}
 
 
function isReadable (obj) {
  return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
}
 
 
function isWritable (obj) {
  return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
}
 
 
function isDuplex (obj) {
  return isReadable(obj) && isWritable(obj)
}
 
 
module.exports            = isStream
module.exports.isReadable = isReadable
module.exports.isWritable = isWritable
module.exports.isDuplex   = isDuplex
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/json-stringify-safe/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/json-stringify-safe/

Statements: 20% (4 / 20)      Branches: 0% (0 / 14)      Functions: 0% (0 / 4)      Lines: 23.53% (4 / 17)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/json-stringify-safe/
File Statements Branches Functions Lines
stringify.js 20% (4 / 20) 0% (0 / 14) 0% (0 / 4) 23.53% (4 / 17)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/json-stringify-safe/stringify.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/json-stringify-safe/stringify.js

Statements: 20% (4 / 20)      Branches: 0% (0 / 14)      Functions: 0% (0 / 4)      Lines: 23.53% (4 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 291 1   1       1                                          
exports = module.exports = stringify
exports.getSerialize = serializer
 
function stringify(obj, replacer, spaces, cycleReplacer) {
  return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
}
 
function serializer(replacer, cycleReplacer) {
  var stack = [], keys = []
 
  if (cycleReplacer == null) cycleReplacer = function(key, value) {
    if (stack[0] === value) return "[Circular ~]"
    return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
  }
 
  return function(key, value) {
    if (stack.length > 0) {
      var thisPos = stack.indexOf(this)
      ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
      ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
      if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
    }
    else stack.push(value)
 
    return replacer == null ? value : replacer.call(this, key, value)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/

Statements: 50% (32 / 64)      Branches: 21.43% (12 / 56)      Functions: 33.33% (2 / 6)      Lines: 50.79% (32 / 63)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/
File Statements Branches Functions Lines
index.js 50% (32 / 64) 21.43% (12 / 56) 33.33% (2 / 6) 50.79% (32 / 63)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/index.js

Statements: 50% (32 / 64)      Branches: 21.43% (12 / 56)      Functions: 33.33% (2 / 6)      Lines: 50.79% (32 / 63)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190                            1 1             1 1             1 1 1 1 1 1 1     1                 1                                                       1                                                           1                                                 1                                           1   1   1 1920 1920   1920 1100       820     820 1069   1069 22 22   22     12         1057          
/*!
 * mime-types
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */
 
'use strict'
 
/**
 * Module dependencies.
 * @private
 */
 
var db = require('mime-db')
var extname = require('path').extname
 
/**
 * Module variables.
 * @private
 */
 
var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/
var textTypeRegExp = /^text\//i
 
/**
 * Module exports.
 * @public
 */
 
exports.charset = charset
exports.charsets = { lookup: charset }
exports.contentType = contentType
exports.extension = extension
exports.extensions = Object.create(null)
exports.lookup = lookup
exports.types = Object.create(null)
 
// Populate the extensions/types maps
populateMaps(exports.extensions, exports.types)
 
/**
 * Get the default charset for a MIME type.
 *
 * @param {string} type
 * @return {boolean|string}
 */
 
function charset (type) {
  if (!type || typeof type !== 'string') {
    return false
  }
 
  // TODO: use media-typer
  var match = extractTypeRegExp.exec(type)
  var mime = match && db[match[1].toLowerCase()]
 
  if (mime && mime.charset) {
    return mime.charset
  }
 
  // default text/* to utf-8
  if (match && textTypeRegExp.test(match[1])) {
    return 'UTF-8'
  }
 
  return false
}
 
/**
 * Create a full Content-Type header given a MIME type or extension.
 *
 * @param {string} str
 * @return {boolean|string}
 */
 
function contentType (str) {
  // TODO: should this even be in this module?
  if (!str || typeof str !== 'string') {
    return false
  }
 
  var mime = str.indexOf('/') === -1
    ? exports.lookup(str)
    : str
 
  if (!mime) {
    return false
  }
 
  // TODO: use content-type or other module
  if (mime.indexOf('charset') === -1) {
    var charset = exports.charset(mime)
    if (charset) mime += '; charset=' + charset.toLowerCase()
  }
 
  return mime
}
 
/**
 * Get the default extension for a MIME type.
 *
 * @param {string} type
 * @return {boolean|string}
 */
 
function extension (type) {
  if (!type || typeof type !== 'string') {
    return false
  }
 
  // TODO: use media-typer
  var match = extractTypeRegExp.exec(type)
 
  // get extensions
  var exts = match && exports.extensions[match[1].toLowerCase()]
 
  if (!exts || !exts.length) {
    return false
  }
 
  return exts[0]
}
 
/**
 * Lookup the MIME type for a file path/extension.
 *
 * @param {string} path
 * @return {boolean|string}
 */
 
function lookup (path) {
  if (!path || typeof path !== 'string') {
    return false
  }
 
  // get the extension ("ext" or ".ext" or full path)
  var extension = extname('x.' + path)
    .toLowerCase()
    .substr(1)
 
  if (!extension) {
    return false
  }
 
  return exports.types[extension] || false
}
 
/**
 * Populate the extensions and types maps.
 * @private
 */
 
function populateMaps (extensions, types) {
  // source preference (least -> most)
  var preference = ['nginx', 'apache', undefined, 'iana']
 
  Object.keys(db).forEach(function forEachMimeType (type) {
    var mime = db[type]
    var exts = mime.extensions
 
    if (!exts || !exts.length) {
      return
    }
 
    // mime -> extensions
    extensions[type] = exts
 
    // extension -> mime
    for (var i = 0; i < exts.length; i++) {
      var extension = exts[i]
 
      if (types[extension]) {
        var from = preference.indexOf(db[types[extension]].source)
        var to = preference.indexOf(mime.source)
 
        if (types[extension] !== 'application/octet-stream' &&
          from > to || (from === to && types[extension].substr(0, 12) === 'application/')) {
          // skip the remapping
          continue
        }
      }
 
      // set the extension -> mime
      types[extension] = type
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/node_modules/mime-db/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/node_modules/mime-db/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/node_modules/mime-db/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/node_modules/mime-db/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/mime-types/node_modules/mime-db/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13                    1    
/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = require('./db.json')
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/oauth-sign/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/oauth-sign/

Statements: 29.31% (17 / 58)      Branches: 0% (0 / 28)      Functions: 0% (0 / 13)      Lines: 29.31% (17 / 58)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/oauth-sign/
File Statements Branches Functions Lines
index.js 29.31% (17 / 58) 0% (0 / 28) 0% (0 / 13) 29.31% (17 / 58)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/oauth-sign/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/oauth-sign/index.js

Statements: 29.31% (17 / 58)      Branches: 0% (0 / 28)      Functions: 0% (0 / 13)      Lines: 29.31% (17 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 1381       1       1       1                         1                                 1       1                                                                     1                   1             1                 1                                           1 1 1 1 1 1      
var crypto = require('crypto')
  , qs = require('querystring')
  ;
 
function sha1 (key, body) {
  return crypto.createHmac('sha1', key).update(body).digest('base64')
}
 
function rsa (key, body) {
  return crypto.createSign("RSA-SHA1").update(body).sign(key, 'base64');
}
 
function rfc3986 (str) {
  return encodeURIComponent(str)
    .replace(/!/g,'%21')
    .replace(/\*/g,'%2A')
    .replace(/\(/g,'%28')
    .replace(/\)/g,'%29')
    .replace(/'/g,'%27')
    ;
}
 
// Maps object to bi-dimensional array
// Converts { foo: 'A', bar: [ 'b', 'B' ]} to
// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ]
function map (obj) {
  var key, val, arr = []
  for (key in obj) {
    val = obj[key]
    if (Array.isArray(val))
      for (var i = 0; i < val.length; i++)
        arr.push([key, val[i]])
    else if (typeof val === "object")
      for (var prop in val)
        arr.push([key + '[' + prop + ']', val[prop]]);
    else
      arr.push([key, val])
  }
  return arr
}
 
// Compare function for sort
function compare (a, b) {
  return a > b ? 1 : a < b ? -1 : 0
}
 
function generateBase (httpMethod, base_uri, params) {
  // adapted from https://dev.twitter.com/docs/auth/oauth and 
  // https://dev.twitter.com/docs/auth/creating-signature
 
  // Parameter normalization
  // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
  var normalized = map(params)
  // 1.  First, the name and value of each parameter are encoded
  .map(function (p) {
    return [ rfc3986(p[0]), rfc3986(p[1] || '') ]
  })
  // 2.  The parameters are sorted by name, using ascending byte value
  //     ordering.  If two or more parameters share the same name, they
  //     are sorted by their value.
  .sort(function (a, b) {
    return compare(a[0], b[0]) || compare(a[1], b[1])
  })
  // 3.  The name of each parameter is concatenated to its corresponding
  //     value using an "=" character (ASCII code 61) as a separator, even
  //     if the value is empty.
  .map(function (p) { return p.join('=') })
   // 4.  The sorted name/value pairs are concatenated together into a
   //     single string by using an "&" character (ASCII code 38) as
   //     separator.
  .join('&')
 
  var base = [
    rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'),
    rfc3986(base_uri),
    rfc3986(normalized)
  ].join('&')
 
  return base
}
 
function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) {
  var base = generateBase(httpMethod, base_uri, params)
  var key = [
    consumer_secret || '',
    token_secret || ''
  ].map(rfc3986).join('&')
 
  return sha1(key, base)
}
 
function rsasign (httpMethod, base_uri, params, private_key, token_secret) {
  var base = generateBase(httpMethod, base_uri, params)
  var key = private_key || ''
 
  return rsa(key, base)
}
 
function plaintext (consumer_secret, token_secret) {
  var key = [
    consumer_secret || '',
    token_secret || ''
  ].map(rfc3986).join('&')
 
  return key
}
 
function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
  var method
  var skipArgs = 1
 
  switch (signMethod) {
    case 'RSA-SHA1':
      method = rsasign
      break
    case 'HMAC-SHA1':
      method = hmacsign
      break
    case 'PLAINTEXT':
      method = plaintext
      skipArgs = 4
      break
    default:
     throw new Error("Signature method not supported: " + signMethod)
  }
 
  return method.apply(null, [].slice.call(arguments, skipArgs))
}
 
exports.hmacsign = hmacsign
exports.rsasign = rsasign
exports.plaintext = plaintext
exports.sign = sign
exports.rfc3986 = rfc3986
exports.generateBase = generateBase
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/performance-now/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/performance-now/lib/

Statements: 52.38% (11 / 21)      Branches: 50% (6 / 12)      Functions: 33.33% (2 / 6)      Lines: 52.38% (11 / 21)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/performance-now/lib/
File Statements Branches Functions Lines
performance-now.js 52.38% (11 / 21) 50% (6 / 12) 33.33% (2 / 6) 52.38% (11 / 21)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/performance-now/lib/performance-now.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/performance-now/lib/performance-now.js

Statements: 52.38% (11 / 21)      Branches: 50% (6 / 12)      Functions: 33.33% (2 / 6)      Lines: 52.38% (11 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  1 1   1       1 1     1 1 1 1 1   1                              
// Generated by CoffeeScript 1.7.1
(function() {
  var getNanoSeconds, hrtime, loadTime;
 
  Iif ((typeof performance !== "undefined" && performance !== null) && performance.now) {
    module.exports = function() {
      return performance.now();
    };
  } else Eif ((typeof process !== "undefined" && process !== null) && process.hrtime) {
    module.exports = function() {
      return (getNanoSeconds() - loadTime) / 1e6;
    };
    hrtime = process.hrtime;
    getNanoSeconds = function() {
      var hr;
      hr = hrtime();
      return hr[0] * 1e9 + hr[1];
    };
    loadTime = getNanoSeconds();
  } else if (Date.now) {
    module.exports = function() {
      return Date.now() - loadTime;
    };
    loadTime = Date.now();
  } else {
    module.exports = function() {
      return new Date().getTime() - loadTime;
    };
    loadTime = new Date().getTime();
  }
 
}).call(this);
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/

Statements: 12.41% (34 / 274)      Branches: 0.75% (2 / 265)      Functions: 4.35% (1 / 23)      Lines: 12.41% (34 / 274)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/
File Statements Branches Functions Lines
formats.js 60% (3 / 5) 100% (0 / 0) 0% (0 / 2) 60% (3 / 5)
index.js 100% (4 / 4) 100% (0 / 0) 100% (0 / 0) 100% (4 / 4)
parse.js 8.43% (7 / 83) 0% (0 / 90) 0% (0 / 4) 8.43% (7 / 83)
stringify.js 8.05% (7 / 87) 0% (0 / 89) 0% (0 / 6) 8.05% (7 / 87)
utils.js 13.68% (13 / 95) 2.33% (2 / 86) 9.09% (1 / 11) 13.68% (13 / 95)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/formats.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/formats.js

Statements: 60% (3 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 60% (3 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20    1 1   1                            
'use strict';
 
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
 
module.exports = {
    'default': 'RFC3986',
    formatters: {
        RFC1738: function (value) {
            return replace.call(value, percentTwenties, '+');
        },
        RFC3986: function (value) {
            return value;
        }
    },
    RFC1738: 'RFC1738',
    RFC3986: 'RFC3986'
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/index.js

Statements: 100% (4 / 4)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (4 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13    1 1 1   1            
'use strict';
 
var stringify = require('./stringify');
var parse = require('./parse');
var formats = require('./formats');
 
module.exports = {
    formats: formats,
    parse: parse,
    stringify: stringify
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/parse.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/parse.js

Statements: 8.43% (7 / 83)      Branches: 0% (0 / 90)      Functions: 0% (0 / 4)      Lines: 8.43% (7 / 83)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169    1   1   1                       1                                                   1                                                               1                                                                                                             1                                                                          
'use strict';
 
var utils = require('./utils');
 
var has = Object.prototype.hasOwnProperty;
 
var defaults = {
    allowDots: false,
    allowPrototypes: false,
    arrayLimit: 20,
    decoder: utils.decode,
    delimiter: '&',
    depth: 5,
    parameterLimit: 1000,
    plainObjects: false,
    strictNullHandling: false
};
 
var parseValues = function parseQueryStringValues(str, options) {
    var obj = {};
    var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
 
    for (var i = 0; i < parts.length; ++i) {
        var part = parts[i];
        var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
 
        var key, val;
        if (pos === -1) {
            key = options.decoder(part);
            val = options.strictNullHandling ? null : '';
        } else {
            key = options.decoder(part.slice(0, pos));
            val = options.decoder(part.slice(pos + 1));
        }
        if (has.call(obj, key)) {
            obj[key] = [].concat(obj[key]).concat(val);
        } else {
            obj[key] = val;
        }
    }
 
    return obj;
};
 
var parseObject = function parseObjectRecursive(chain, val, options) {
    if (!chain.length) {
        return val;
    }
 
    var root = chain.shift();
 
    var obj;
    if (root === '[]') {
        obj = [];
        obj = obj.concat(parseObject(chain, val, options));
    } else {
        obj = options.plainObjects ? Object.create(null) : {};
        var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
        var index = parseInt(cleanRoot, 10);
        if (
            !isNaN(index) &&
            root !== cleanRoot &&
            String(index) === cleanRoot &&
            index >= 0 &&
            (options.parseArrays && index <= options.arrayLimit)
        ) {
            obj = [];
            obj[index] = parseObject(chain, val, options);
        } else {
            obj[cleanRoot] = parseObject(chain, val, options);
        }
    }
 
    return obj;
};
 
var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
    if (!givenKey) {
        return;
    }
 
    // Transform dot notation to bracket notation
    var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
 
    // The regex chunks
 
    var brackets = /(\[[^[\]]*])/;
    var child = /(\[[^[\]]*])/g;
 
    // Get the parent
 
    var segment = brackets.exec(key);
    var parent = segment ? key.slice(0, segment.index) : key;
 
    // Stash the parent if it exists
 
    var keys = [];
    if (parent) {
        // If we aren't using plain objects, optionally prefix keys
        // that would overwrite object prototype properties
        if (!options.plainObjects && has.call(Object.prototype, parent)) {
            if (!options.allowPrototypes) {
                return;
            }
        }
 
        keys.push(parent);
    }
 
    // Loop through children appending to the array until we hit depth
 
    var i = 0;
    while ((segment = child.exec(key)) !== null && i < options.depth) {
        i += 1;
        if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
            if (!options.allowPrototypes) {
                return;
            }
        }
        keys.push(segment[1]);
    }
 
    // If there's a remainder, just add whatever is left
 
    if (segment) {
        keys.push('[' + key.slice(segment.index) + ']');
    }
 
    return parseObject(keys, val, options);
};
 
module.exports = function (str, opts) {
    var options = opts || {};
 
    if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
        throw new TypeError('Decoder has to be a function.');
    }
 
    options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
    options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
    options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
    options.parseArrays = options.parseArrays !== false;
    options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
    options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
    options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
    options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
    options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
    options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
 
    if (str === '' || str === null || typeof str === 'undefined') {
        return options.plainObjects ? Object.create(null) : {};
    }
 
    var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
    var obj = options.plainObjects ? Object.create(null) : {};
 
    // Iterate over the keys and setup the new object
 
    var keys = Object.keys(tempObj);
    for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var newObj = parseKeys(key, tempObj[key], options);
        obj = utils.merge(obj, newObj, options);
    }
 
    return utils.compact(obj);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/stringify.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/stringify.js

Statements: 8.05% (7 / 87)      Branches: 0% (0 / 89)      Functions: 0% (0 / 6)      Lines: 8.05% (7 / 87)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209    1 1   1                       1   1                       1                                                                                                                                                                                       1                                                                                                                                                                          
'use strict';
 
var utils = require('./utils');
var formats = require('./formats');
 
var arrayPrefixGenerators = {
    brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
        return prefix + '[]';
    },
    indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
        return prefix + '[' + key + ']';
    },
    repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
        return prefix;
    }
};
 
var toISO = Date.prototype.toISOString;
 
var defaults = {
    delimiter: '&',
    encode: true,
    encoder: utils.encode,
    encodeValuesOnly: false,
    serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
        return toISO.call(date);
    },
    skipNulls: false,
    strictNullHandling: false
};
 
var stringify = function stringify( // eslint-disable-line func-name-matching
    object,
    prefix,
    generateArrayPrefix,
    strictNullHandling,
    skipNulls,
    encoder,
    filter,
    sort,
    allowDots,
    serializeDate,
    formatter,
    encodeValuesOnly
) {
    var obj = object;
    if (typeof filter === 'function') {
        obj = filter(prefix, obj);
    } else if (obj instanceof Date) {
        obj = serializeDate(obj);
    } else if (obj === null) {
        if (strictNullHandling) {
            return encoder && !encodeValuesOnly ? encoder(prefix) : prefix;
        }
 
        obj = '';
    }
 
    if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
        if (encoder) {
            var keyValue = encodeValuesOnly ? prefix : encoder(prefix);
            return [formatter(keyValue) + '=' + formatter(encoder(obj))];
        }
        return [formatter(prefix) + '=' + formatter(String(obj))];
    }
 
    var values = [];
 
    if (typeof obj === 'undefined') {
        return values;
    }
 
    var objKeys;
    if (Array.isArray(filter)) {
        objKeys = filter;
    } else {
        var keys = Object.keys(obj);
        objKeys = sort ? keys.sort(sort) : keys;
    }
 
    for (var i = 0; i < objKeys.length; ++i) {
        var key = objKeys[i];
 
        if (skipNulls && obj[key] === null) {
            continue;
        }
 
        if (Array.isArray(obj)) {
            values = values.concat(stringify(
                obj[key],
                generateArrayPrefix(prefix, key),
                generateArrayPrefix,
                strictNullHandling,
                skipNulls,
                encoder,
                filter,
                sort,
                allowDots,
                serializeDate,
                formatter,
                encodeValuesOnly
            ));
        } else {
            values = values.concat(stringify(
                obj[key],
                prefix + (allowDots ? '.' + key : '[' + key + ']'),
                generateArrayPrefix,
                strictNullHandling,
                skipNulls,
                encoder,
                filter,
                sort,
                allowDots,
                serializeDate,
                formatter,
                encodeValuesOnly
            ));
        }
    }
 
    return values;
};
 
module.exports = function (object, opts) {
    var obj = object;
    var options = opts || {};
 
    if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
        throw new TypeError('Encoder has to be a function.');
    }
 
    var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
    var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
    var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
    var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
    var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder;
    var sort = typeof options.sort === 'function' ? options.sort : null;
    var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
    var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
    var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
    if (typeof options.format === 'undefined') {
        options.format = formats.default;
    } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
        throw new TypeError('Unknown format option provided.');
    }
    var formatter = formats.formatters[options.format];
    var objKeys;
    var filter;
 
    if (typeof options.filter === 'function') {
        filter = options.filter;
        obj = filter('', obj);
    } else if (Array.isArray(options.filter)) {
        filter = options.filter;
        objKeys = filter;
    }
 
    var keys = [];
 
    if (typeof obj !== 'object' || obj === null) {
        return '';
    }
 
    var arrayFormat;
    if (options.arrayFormat in arrayPrefixGenerators) {
        arrayFormat = options.arrayFormat;
    } else if ('indices' in options) {
        arrayFormat = options.indices ? 'indices' : 'repeat';
    } else {
        arrayFormat = 'indices';
    }
 
    var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
 
    if (!objKeys) {
        objKeys = Object.keys(obj);
    }
 
    if (sort) {
        objKeys.sort(sort);
    }
 
    for (var i = 0; i < objKeys.length; ++i) {
        var key = objKeys[i];
 
        if (skipNulls && obj[key] === null) {
            continue;
        }
 
        keys = keys.concat(stringify(
            obj[key],
            key,
            generateArrayPrefix,
            strictNullHandling,
            skipNulls,
            encode ? encoder : null,
            filter,
            sort,
            allowDots,
            serializeDate,
            formatter,
            encodeValuesOnly
        ));
    }
 
    return keys.join(delimiter);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/utils.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/qs/lib/utils.js

Statements: 13.68% (13 / 95)      Branches: 2.33% (2 / 86)      Functions: 9.09% (1 / 11)      Lines: 13.68% (13 / 95)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184    1   1 1 1 256     1     1                     1                                                                                                             1               1                                                                                                 1                                                                     1       1                
'use strict';
 
var has = Object.prototype.hasOwnProperty;
 
var hexTable = (function () {
    var array = [];
    for (var i = 0; i < 256; ++i) {
        array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
    }
 
    return array;
}());
 
exports.arrayToObject = function (source, options) {
    var obj = options && options.plainObjects ? Object.create(null) : {};
    for (var i = 0; i < source.length; ++i) {
        if (typeof source[i] !== 'undefined') {
            obj[i] = source[i];
        }
    }
 
    return obj;
};
 
exports.merge = function (target, source, options) {
    if (!source) {
        return target;
    }
 
    if (typeof source !== 'object') {
        if (Array.isArray(target)) {
            target.push(source);
        } else if (typeof target === 'object') {
            if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
                target[source] = true;
            }
        } else {
            return [target, source];
        }
 
        return target;
    }
 
    if (typeof target !== 'object') {
        return [target].concat(source);
    }
 
    var mergeTarget = target;
    if (Array.isArray(target) && !Array.isArray(source)) {
        mergeTarget = exports.arrayToObject(target, options);
    }
 
    if (Array.isArray(target) && Array.isArray(source)) {
        source.forEach(function (item, i) {
            if (has.call(target, i)) {
                if (target[i] && typeof target[i] === 'object') {
                    target[i] = exports.merge(target[i], item, options);
                } else {
                    target.push(item);
                }
            } else {
                target[i] = item;
            }
        });
        return target;
    }
 
    return Object.keys(source).reduce(function (acc, key) {
        var value = source[key];
 
        if (Object.prototype.hasOwnProperty.call(acc, key)) {
            acc[key] = exports.merge(acc[key], value, options);
        } else {
            acc[key] = value;
        }
        return acc;
    }, mergeTarget);
};
 
exports.decode = function (str) {
    try {
        return decodeURIComponent(str.replace(/\+/g, ' '));
    } catch (e) {
        return str;
    }
};
 
exports.encode = function (str) {
    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
    // It has been adapted here for stricter adherence to RFC 3986
    if (str.length === 0) {
        return str;
    }
 
    var string = typeof str === 'string' ? str : String(str);
 
    var out = '';
    for (var i = 0; i < string.length; ++i) {
        var c = string.charCodeAt(i);
 
        if (
            c === 0x2D || // -
            c === 0x2E || // .
            c === 0x5F || // _
            c === 0x7E || // ~
            (c >= 0x30 && c <= 0x39) || // 0-9
            (c >= 0x41 && c <= 0x5A) || // a-z
            (c >= 0x61 && c <= 0x7A) // A-Z
        ) {
            out += string.charAt(i);
            continue;
        }
 
        if (c < 0x80) {
            out = out + hexTable[c];
            continue;
        }
 
        if (c < 0x800) {
            out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
            continue;
        }
 
        if (c < 0xD800 || c >= 0xE000) {
            out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
            continue;
        }
 
        i += 1;
        c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
        out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; // eslint-disable-line max-len
    }
 
    return out;
};
 
exports.compact = function (obj, references) {
    if (typeof obj !== 'object' || obj === null) {
        return obj;
    }
 
    var refs = references || [];
    var lookup = refs.indexOf(obj);
    if (lookup !== -1) {
        return refs[lookup];
    }
 
    refs.push(obj);
 
    if (Array.isArray(obj)) {
        var compacted = [];
 
        for (var i = 0; i < obj.length; ++i) {
            if (obj[i] && typeof obj[i] === 'object') {
                compacted.push(exports.compact(obj[i], refs));
            } else if (typeof obj[i] !== 'undefined') {
                compacted.push(obj[i]);
            }
        }
 
        return compacted;
    }
 
    var keys = Object.keys(obj);
    keys.forEach(function (key) {
        obj[key] = exports.compact(obj[key], refs);
    });
 
    return obj;
};
 
exports.isRegExp = function (obj) {
    return Object.prototype.toString.call(obj) === '[object RegExp]';
};
 
exports.isBuffer = function (obj) {
    if (obj === null || typeof obj === 'undefined') {
        return false;
    }
 
    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/safe-buffer/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/safe-buffer/

Statements: 31.25% (10 / 32)      Branches: 27.78% (5 / 18)      Functions: 14.29% (1 / 7)      Lines: 31.25% (10 / 32)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/safe-buffer/
File Statements Branches Functions Lines
index.js 31.25% (10 / 32) 27.78% (5 / 18) 14.29% (1 / 7) 31.25% (10 / 32)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/safe-buffer/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/safe-buffer/index.js

Statements: 31.25% (10 / 32)      Branches: 27.78% (5 / 18)      Functions: 14.29% (1 / 7)      Lines: 31.25% (10 / 32)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601   1 1                 1         1 10     1             1                                 1             1              
var buffer = require('buffer')
 
Eif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  Object.keys(buffer).forEach(function (prop) {
    exports[prop] = buffer[prop]
  })
  exports.Buffer = SafeBuffer
}
 
function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}
 
// Copy static methods from Buffer
Object.keys(Buffer).forEach(function (prop) {
  SafeBuffer[prop] = Buffer[prop]
})
 
SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
}
 
SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size)
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
  } else {
    buf.fill(0)
  }
  return buf
}
 
SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
}
 
SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer.SlowBuffer(size)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/stringstream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/stringstream/

Statements: 22.08% (17 / 77)      Branches: 0% (0 / 35)      Functions: 0% (0 / 10)      Lines: 25% (17 / 68)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/stringstream/
File Statements Branches Functions Lines
stringstream.js 22.08% (17 / 77) 0% (0 / 35) 0% (0 / 10) 25% (17 / 68)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/stringstream/stringstream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/stringstream/stringstream.js

Statements: 22.08% (17 / 77)      Branches: 0% (0 / 35)      Functions: 0% (0 / 10)      Lines: 25% (17 / 68)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 1041 1 1   1 1   1                         1   1                               1             1               1           1       1         1                     1   1             1                              
var util = require('util')
var Stream = require('stream')
var StringDecoder = require('string_decoder').StringDecoder
 
module.exports = StringStream
module.exports.AlignedStringDecoder = AlignedStringDecoder
 
function StringStream(from, to) {
  if (!(this instanceof StringStream)) return new StringStream(from, to)
 
  Stream.call(this)
 
  if (from == null) from = 'utf8'
 
  this.readable = this.writable = true
  this.paused = false
  this.toEncoding = (to == null ? from : to)
  this.fromEncoding = (to == null ? '' : from)
  this.decoder = new AlignedStringDecoder(this.toEncoding)
}
util.inherits(StringStream, Stream)
 
StringStream.prototype.write = function(data) {
  if (!this.writable) {
    var err = new Error('stream not writable')
    err.code = 'EPIPE'
    this.emit('error', err)
    return false
  }
  if (this.fromEncoding) {
    if (Buffer.isBuffer(data)) data = data.toString()
    data = new Buffer(data, this.fromEncoding)
  }
  var string = this.decoder.write(data)
  if (string.length) this.emit('data', string)
  return !this.paused
}
 
StringStream.prototype.flush = function() {
  if (this.decoder.flush) {
    var string = this.decoder.flush()
    if (string.length) this.emit('data', string)
  }
}
 
StringStream.prototype.end = function() {
  if (!this.writable && !this.readable) return
  this.flush()
  this.emit('end')
  this.writable = this.readable = false
  this.destroy()
}
 
StringStream.prototype.destroy = function() {
  this.decoder = null
  this.writable = this.readable = false
  this.emit('close')
}
 
StringStream.prototype.pause = function() {
  this.paused = true
}
 
StringStream.prototype.resume = function () {
  if (this.paused) this.emit('drain')
  this.paused = false
}
 
function AlignedStringDecoder(encoding) {
  StringDecoder.call(this, encoding)
 
  switch (this.encoding) {
    case 'base64':
      this.write = alignedWrite
      this.alignedBuffer = new Buffer(3)
      this.alignedBytes = 0
      break
  }
}
util.inherits(AlignedStringDecoder, StringDecoder)
 
AlignedStringDecoder.prototype.flush = function() {
  if (!this.alignedBuffer || !this.alignedBytes) return ''
  var leftover = this.alignedBuffer.toString(this.encoding, 0, this.alignedBytes)
  this.alignedBytes = 0
  return leftover
}
 
function alignedWrite(buffer) {
  var rem = (this.alignedBytes + buffer.length) % this.alignedBuffer.length
  if (!rem && !this.alignedBytes) return buffer.toString(this.encoding)
 
  var returnBuffer = new Buffer(this.alignedBytes + buffer.length - rem)
 
  this.alignedBuffer.copy(returnBuffer, 0, 0, this.alignedBytes)
  buffer.copy(returnBuffer, this.alignedBytes, 0, buffer.length - rem)
 
  buffer.copy(this.alignedBuffer, 0, buffer.length - rem, buffer.length)
  this.alignedBytes = rem
 
  return returnBuffer.toString(this.encoding)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/

Statements: 19.26% (146 / 758)      Branches: 1.55% (8 / 515)      Functions: 6.9% (6 / 87)      Lines: 19.36% (146 / 754)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/
File Statements Branches Functions Lines
cookie.js 18.14% (109 / 601) 1.79% (8 / 446) 6.78% (4 / 59) 18.26% (109 / 597)
memstore.js 24.68% (19 / 77) 0% (0 / 35) 5.88% (1 / 17) 24.68% (19 / 77)
pathMatch.js 18.18% (2 / 11) 0% (0 / 8) 0% (0 / 1) 18.18% (2 / 11)
permuteDomain.js 18.75% (3 / 16) 0% (0 / 4) 0% (0 / 1) 18.75% (3 / 16)
pubsuffix.js 8.33% (3 / 36) 0% (0 / 22) 0% (0 / 1) 8.33% (3 / 36)
store.js 58.82% (10 / 17) 100% (0 / 0) 12.5% (1 / 8) 58.82% (10 / 17)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/cookie.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/cookie.js

Statements: 18.14% (109 / 601)      Branches: 1.79% (8 / 446)      Functions: 6.78% (4 / 59)      Lines: 18.26% (109 / 597)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338                                                              1 1 1 1 1 1 1   1 1 1         1       1 1   1             1       1       1   1 1 1   1       1     1       1   1 1       1                                                                                                                                                                                                                                                     1                     1                             1                                                                                                             1                                               1                                                                                                                                                                                                                                                                                                                   1                   1                                                                                                       1                                                     1                                       1                               1                                             1   1 1   1 1     1 1 1 1 1 1 1     1 1 1 1 1             1   13             1                 1                                                                       1       1                                                     1               1                 1                       1                                                                                 1                                                       1                             1                       1         1               1 1   1     1     1 1     1 1   1   1 1 1 1   1 1                                                                                                                                                               1                                                                       1 1                                                     1                                                                                                                                     1 1                                     1 1                               1 1                                                                                                 1         1 1             1                                                   1                                                   1                         1   1 1                             1 7                                         1 7     1                                      
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';
var net = require('net');
var urlParse = require('url').parse;
var pubsuffix = require('./pubsuffix');
var Store = require('./store').Store;
var MemoryCookieStore = require('./memstore').MemoryCookieStore;
var pathMatch = require('./pathMatch').pathMatch;
var VERSION = require('../package.json').version;
 
var punycode;
try {
  punycode = require('punycode');
} catch(e) {
  console.warn("cookie: can't load punycode; won't use punycode for domain normalization");
}
 
var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
 
// From RFC6265 S4.1.1
// note that it excludes \x3B ";"
var COOKIE_OCTET  = /[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/;
var COOKIE_OCTETS = new RegExp('^'+COOKIE_OCTET.source+'+$');
 
var CONTROL_CHARS = /[\x00-\x1F]/;
 
// Double quotes are part of the value (see: S4.1.1).
// '\r', '\n' and '\0' should be treated as a terminator in the "relaxed" mode
// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60)
// '=' and ';' are attribute/values separators
// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L64)
var COOKIE_PAIR = /^(([^=;]+))\s*=\s*([^\n\r\0]*)/;
 
// Used to parse non-RFC-compliant cookies like '=abc' when given the `loose`
// option in Cookie.parse:
var LOOSE_COOKIE_PAIR = /^((?:=)?([^=;]*)\s*=\s*)?([^\n\r\0]*)/;
 
// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
// Note ';' is \x3B
var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
 
var DAY_OF_MONTH = /^(\d{1,2})[^\d]*$/;
var TIME = /^(\d{1,2})[^\d]*:(\d{1,2})[^\d]*:(\d{1,2})[^\d]*$/;
var MONTH = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i;
 
var MONTH_TO_NUM = {
  jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
  jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
};
var NUM_TO_MONTH = [
  'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
];
var NUM_TO_DAY = [
  'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
];
 
var YEAR = /^(\d{2}|\d{4})$/; // 2 to 4 digits
 
var MAX_TIME = 2147483647000; // 31-bit max
var MIN_TIME = 0; // 31-bit min
 
 
// RFC6265 S5.1.1 date parser:
function parseDate(str) {
  if (!str) {
    return;
  }
 
  /* RFC6265 S5.1.1:
   * 2. Process each date-token sequentially in the order the date-tokens
   * appear in the cookie-date
   */
  var tokens = str.split(DATE_DELIM);
  if (!tokens) {
    return;
  }
 
  var hour = null;
  var minutes = null;
  var seconds = null;
  var day = null;
  var month = null;
  var year = null;
 
  for (var i=0; i<tokens.length; i++) {
    var token = tokens[i].trim();
    if (!token.length) {
      continue;
    }
 
    var result;
 
    /* 2.1. If the found-time flag is not set and the token matches the time
     * production, set the found-time flag and set the hour- value,
     * minute-value, and second-value to the numbers denoted by the digits in
     * the date-token, respectively.  Skip the remaining sub-steps and continue
     * to the next date-token.
     */
    if (seconds === null) {
      result = TIME.exec(token);
      if (result) {
        hour = parseInt(result[1], 10);
        minutes = parseInt(result[2], 10);
        seconds = parseInt(result[3], 10);
        /* RFC6265 S5.1.1.5:
         * [fail if]
         * *  the hour-value is greater than 23,
         * *  the minute-value is greater than 59, or
         * *  the second-value is greater than 59.
         */
        if(hour > 23 || minutes > 59 || seconds > 59) {
          return;
        }
 
        continue;
      }
    }
 
    /* 2.2. If the found-day-of-month flag is not set and the date-token matches
     * the day-of-month production, set the found-day-of- month flag and set
     * the day-of-month-value to the number denoted by the date-token.  Skip
     * the remaining sub-steps and continue to the next date-token.
     */
    if (day === null) {
      result = DAY_OF_MONTH.exec(token);
      if (result) {
        day = parseInt(result, 10);
        /* RFC6265 S5.1.1.5:
         * [fail if] the day-of-month-value is less than 1 or greater than 31
         */
        if(day < 1 || day > 31) {
          return;
        }
        continue;
      }
    }
 
    /* 2.3. If the found-month flag is not set and the date-token matches the
     * month production, set the found-month flag and set the month-value to
     * the month denoted by the date-token.  Skip the remaining sub-steps and
     * continue to the next date-token.
     */
    if (month === null) {
      result = MONTH.exec(token);
      if (result) {
        month = MONTH_TO_NUM[result[1].toLowerCase()];
        continue;
      }
    }
 
    /* 2.4. If the found-year flag is not set and the date-token matches the year
     * production, set the found-year flag and set the year-value to the number
     * denoted by the date-token.  Skip the remaining sub-steps and continue to
     * the next date-token.
     */
    if (year === null) {
      result = YEAR.exec(token);
      if (result) {
        year = parseInt(result[0], 10);
        /* From S5.1.1:
         * 3.  If the year-value is greater than or equal to 70 and less
         * than or equal to 99, increment the year-value by 1900.
         * 4.  If the year-value is greater than or equal to 0 and less
         * than or equal to 69, increment the year-value by 2000.
         */
        if (70 <= year && year <= 99) {
          year += 1900;
        } else if (0 <= year && year <= 69) {
          year += 2000;
        }
 
        if (year < 1601) {
          return; // 5. ... the year-value is less than 1601
        }
      }
    }
  }
 
  if (seconds === null || day === null || month === null || year === null) {
    return; // 5. ... at least one of the found-day-of-month, found-month, found-
            // year, or found-time flags is not set,
  }
 
  return new Date(Date.UTC(year, month, day, hour, minutes, seconds));
}
 
function formatDate(date) {
  var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
  var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
  var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
  var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
  return NUM_TO_DAY[date.getUTCDay()] + ', ' +
    d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
    h+':'+m+':'+s+' GMT';
}
 
// S5.1.2 Canonicalized Host Names
function canonicalDomain(str) {
  if (str == null) {
    return null;
  }
  str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
 
  // convert to IDN if any non-ASCII characters
  if (punycode && /[^\u0001-\u007f]/.test(str)) {
    str = punycode.toASCII(str);
  }
 
  return str.toLowerCase();
}
 
// S5.1.3 Domain Matching
function domainMatch(str, domStr, canonicalize) {
  if (str == null || domStr == null) {
    return null;
  }
  if (canonicalize !== false) {
    str = canonicalDomain(str);
    domStr = canonicalDomain(domStr);
  }
 
  /*
   * "The domain string and the string are identical. (Note that both the
   * domain string and the string will have been canonicalized to lower case at
   * this point)"
   */
  if (str == domStr) {
    return true;
  }
 
  /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
 
  /* "* The string is a host name (i.e., not an IP address)." */
  if (net.isIP(str)) {
    return false;
  }
 
  /* "* The domain string is a suffix of the string" */
  var idx = str.indexOf(domStr);
  if (idx <= 0) {
    return false; // it's a non-match (-1) or prefix (0)
  }
 
  // e.g "a.b.c".indexOf("b.c") === 2
  // 5 === 3+2
  if (str.length !== domStr.length + idx) { // it's not a suffix
    return false;
  }
 
  /* "* The last character of the string that is not included in the domain
  * string is a %x2E (".") character." */
  if (str.substr(idx-1,1) !== '.') {
    return false;
  }
 
  return true;
}
 
 
// RFC6265 S5.1.4 Paths and Path-Match
 
/*
 * "The user agent MUST use an algorithm equivalent to the following algorithm
 * to compute the default-path of a cookie:"
 *
 * Assumption: the path (and not query part or absolute uri) is passed in.
 */
function defaultPath(path) {
  // "2. If the uri-path is empty or if the first character of the uri-path is not
  // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
  if (!path || path.substr(0,1) !== "/") {
    return "/";
  }
 
  // "3. If the uri-path contains no more than one %x2F ("/") character, output
  // %x2F ("/") and skip the remaining step."
  if (path === "/") {
    return path;
  }
 
  var rightSlash = path.lastIndexOf("/");
  if (rightSlash === 0) {
    return "/";
  }
 
  // "4. Output the characters of the uri-path from the first character up to,
  // but not including, the right-most %x2F ("/")."
  return path.slice(0, rightSlash);
}
 
 
function parse(str, options) {
  if (!options || typeof options !== 'object') {
    options = {};
  }
  str = str.trim();
 
  // We use a regex to parse the "name-value-pair" part of S5.2
  var firstSemi = str.indexOf(';'); // S5.2 step 1
  var pairRe = options.loose ? LOOSE_COOKIE_PAIR : COOKIE_PAIR;
  var result = pairRe.exec(firstSemi === -1 ? str : str.substr(0,firstSemi));
 
  // Rx satisfies the "the name string is empty" and "lacks a %x3D ("=")"
  // constraints as well as trimming any whitespace.
  if (!result) {
    return;
  }
 
  var c = new Cookie();
  if (result[1]) {
    c.key = result[2].trim();
  } else {
    c.key = '';
  }
  c.value = result[3].trim();
  if (CONTROL_CHARS.test(c.key) || CONTROL_CHARS.test(c.value)) {
    return;
  }
 
  if (firstSemi === -1) {
    return c;
  }
 
  // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
  // (including the %x3B (";") in question)." plus later on in the same section
  // "discard the first ";" and trim".
  var unparsed = str.slice(firstSemi + 1).trim();
 
  // "If the unparsed-attributes string is empty, skip the rest of these
  // steps."
  if (unparsed.length === 0) {
    return c;
  }
 
  /*
   * S5.2 says that when looping over the items "[p]rocess the attribute-name
   * and attribute-value according to the requirements in the following
   * subsections" for every item.  Plus, for many of the individual attributes
   * in S5.3 it says to use the "attribute-value of the last attribute in the
   * cookie-attribute-list".  Therefore, in this implementation, we overwrite
   * the previous value.
   */
  var cookie_avs = unparsed.split(';');
  while (cookie_avs.length) {
    var av = cookie_avs.shift().trim();
    if (av.length === 0) { // happens if ";;" appears
      continue;
    }
    var av_sep = av.indexOf('=');
    var av_key, av_value;
 
    if (av_sep === -1) {
      av_key = av;
      av_value = null;
    } else {
      av_key = av.substr(0,av_sep);
      av_value = av.substr(av_sep+1);
    }
 
    av_key = av_key.trim().toLowerCase();
 
    if (av_value) {
      av_value = av_value.trim();
    }
 
    switch(av_key) {
    case 'expires': // S5.2.1
      if (av_value) {
        var exp = parseDate(av_value);
        // "If the attribute-value failed to parse as a cookie date, ignore the
        // cookie-av."
        if (exp) {
          // over and underflow not realistically a concern: V8's getTime() seems to
          // store something larger than a 32-bit time_t (even with 32-bit node)
          c.expires = exp;
        }
      }
      break;
 
    case 'max-age': // S5.2.2
      if (av_value) {
        // "If the first character of the attribute-value is not a DIGIT or a "-"
        // character ...[or]... If the remainder of attribute-value contains a
        // non-DIGIT character, ignore the cookie-av."
        if (/^-?[0-9]+$/.test(av_value)) {
          var delta = parseInt(av_value, 10);
          // "If delta-seconds is less than or equal to zero (0), let expiry-time
          // be the earliest representable date and time."
          c.setMaxAge(delta);
        }
      }
      break;
 
    case 'domain': // S5.2.3
      // "If the attribute-value is empty, the behavior is undefined.  However,
      // the user agent SHOULD ignore the cookie-av entirely."
      if (av_value) {
        // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
        // (".") character."
        var domain = av_value.trim().replace(/^\./, '');
        if (domain) {
          // "Convert the cookie-domain to lower case."
          c.domain = domain.toLowerCase();
        }
      }
      break;
 
    case 'path': // S5.2.4
      /*
       * "If the attribute-value is empty or if the first character of the
       * attribute-value is not %x2F ("/"):
       *   Let cookie-path be the default-path.
       * Otherwise:
       *   Let cookie-path be the attribute-value."
       *
       * We'll represent the default-path as null since it depends on the
       * context of the parsing.
       */
      c.path = av_value && av_value[0] === "/" ? av_value : null;
      break;
 
    case 'secure': // S5.2.5
      /*
       * "If the attribute-name case-insensitively matches the string "Secure",
       * the user agent MUST append an attribute to the cookie-attribute-list
       * with an attribute-name of Secure and an empty attribute-value."
       */
      c.secure = true;
      break;
 
    case 'httponly': // S5.2.6 -- effectively the same as 'secure'
      c.httpOnly = true;
      break;
 
    default:
      c.extensions = c.extensions || [];
      c.extensions.push(av);
      break;
    }
  }
 
  return c;
}
 
// avoid the V8 deoptimization monster!
function jsonParse(str) {
  var obj;
  try {
    obj = JSON.parse(str);
  } catch (e) {
    return e;
  }
  return obj;
}
 
function fromJSON(str) {
  if (!str) {
    return null;
  }
 
  var obj;
  if (typeof str === 'string') {
    obj = jsonParse(str);
    if (obj instanceof Error) {
      return null;
    }
  } else {
    // assume it's an Object
    obj = str;
  }
 
  var c = new Cookie();
  for (var i=0; i<Cookie.serializableProperties.length; i++) {
    var prop = Cookie.serializableProperties[i];
    if (obj[prop] === undefined ||
        obj[prop] === Cookie.prototype[prop])
    {
      continue; // leave as prototype default
    }
 
    if (prop === 'expires' ||
        prop === 'creation' ||
        prop === 'lastAccessed')
    {
      if (obj[prop] === null) {
        c[prop] = null;
      } else {
        c[prop] = obj[prop] == "Infinity" ?
          "Infinity" : new Date(obj[prop]);
      }
    } else {
      c[prop] = obj[prop];
    }
  }
 
  return c;
}
 
/* Section 5.4 part 2:
 * "*  Cookies with longer paths are listed before cookies with
 *     shorter paths.
 *
 *  *  Among cookies that have equal-length path fields, cookies with
 *     earlier creation-times are listed before cookies with later
 *     creation-times."
 */
 
function cookieCompare(a,b) {
  var cmp = 0;
 
  // descending for length: b CMP a
  var aPathLen = a.path ? a.path.length : 0;
  var bPathLen = b.path ? b.path.length : 0;
  cmp = bPathLen - aPathLen;
  if (cmp !== 0) {
    return cmp;
  }
 
  // ascending for time: a CMP b
  var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
  var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
  cmp = aTime - bTime;
  if (cmp !== 0) {
    return cmp;
  }
 
  // break ties for the same millisecond (precision of JavaScript's clock)
  cmp = a.creationIndex - b.creationIndex;
 
  return cmp;
}
 
// Gives the permutation of all possible pathMatch()es of a given path. The
// array is in longest-to-shortest order.  Handy for indexing.
function permutePath(path) {
  if (path === '/') {
    return ['/'];
  }
  if (path.lastIndexOf('/') === path.length-1) {
    path = path.substr(0,path.length-1);
  }
  var permutations = [path];
  while (path.length > 1) {
    var lindex = path.lastIndexOf('/');
    if (lindex === 0) {
      break;
    }
    path = path.substr(0,lindex);
    permutations.push(path);
  }
  permutations.push('/');
  return permutations;
}
 
function getCookieContext(url) {
  if (url instanceof Object) {
    return url;
  }
  // NOTE: decodeURI will throw on malformed URIs (see GH-32).
  // Therefore, we will just skip decoding for such URIs.
  try {
    url = decodeURI(url);
  }
  catch(err) {
    // Silently swallow error
  }
 
  return urlParse(url);
}
 
function Cookie(options) {
  options = options || {};
 
  Object.keys(options).forEach(function(prop) {
    if (Cookie.prototype.hasOwnProperty(prop) &&
        Cookie.prototype[prop] !== options[prop] &&
        prop.substr(0,1) !== '_')
    {
      this[prop] = options[prop];
    }
  }, this);
 
  this.creation = this.creation || new Date();
 
  // used to break creation ties in cookieCompare():
  Object.defineProperty(this, 'creationIndex', {
    configurable: false,
    enumerable: false, // important for assert.deepEqual checks
    writable: true,
    value: ++Cookie.cookiesCreated
  });
}
 
Cookie.cookiesCreated = 0; // incremented each time a cookie is created
 
Cookie.parse = parse;
Cookie.fromJSON = fromJSON;
 
Cookie.prototype.key = "";
Cookie.prototype.value = "";
 
// the order in which the RFC has them:
Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
Cookie.prototype.domain = null;
Cookie.prototype.path = null;
Cookie.prototype.secure = false;
Cookie.prototype.httpOnly = false;
Cookie.prototype.extensions = null;
 
// set by the CookieJar:
Cookie.prototype.hostOnly = null; // boolean when set
Cookie.prototype.pathIsDefault = null; // boolean when set
Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
Cookie.prototype.lastAccessed = null; // Date when set
Object.defineProperty(Cookie.prototype, 'creationIndex', {
  configurable: true,
  enumerable: false,
  writable: true,
  value: 0
});
 
Cookie.serializableProperties = Object.keys(Cookie.prototype)
  .filter(function(prop) {
    return !(
      Cookie.prototype[prop] instanceof Function ||
      prop === 'creationIndex' ||
      prop.substr(0,1) === '_'
    );
  });
 
Cookie.prototype.inspect = function inspect() {
  var now = Date.now();
  return 'Cookie="'+this.toString() +
    '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
    '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
    '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
    '"';
};
 
Cookie.prototype.toJSON = function() {
  var obj = {};
 
  var props = Cookie.serializableProperties;
  for (var i=0; i<props.length; i++) {
    var prop = props[i];
    if (this[prop] === Cookie.prototype[prop]) {
      continue; // leave as prototype default
    }
 
    if (prop === 'expires' ||
        prop === 'creation' ||
        prop === 'lastAccessed')
    {
      if (this[prop] === null) {
        obj[prop] = null;
      } else {
        obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
          "Infinity" : this[prop].toISOString();
      }
    } else if (prop === 'maxAge') {
      if (this[prop] !== null) {
        // again, intentionally not ===
        obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
          this[prop].toString() : this[prop];
      }
    } else {
      if (this[prop] !== Cookie.prototype[prop]) {
        obj[prop] = this[prop];
      }
    }
  }
 
  return obj;
};
 
Cookie.prototype.clone = function() {
  return fromJSON(this.toJSON());
};
 
Cookie.prototype.validate = function validate() {
  if (!COOKIE_OCTETS.test(this.value)) {
    return false;
  }
  if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
    return false;
  }
  if (this.maxAge != null && this.maxAge <= 0) {
    return false; // "Max-Age=" non-zero-digit *DIGIT
  }
  if (this.path != null && !PATH_VALUE.test(this.path)) {
    return false;
  }
 
  var cdomain = this.cdomain();
  if (cdomain) {
    if (cdomain.match(/\.$/)) {
      return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
    }
    var suffix = pubsuffix.getPublicSuffix(cdomain);
    if (suffix == null) { // it's a public suffix
      return false;
    }
  }
  return true;
};
 
Cookie.prototype.setExpires = function setExpires(exp) {
  if (exp instanceof Date) {
    this.expires = exp;
  } else {
    this.expires = parseDate(exp) || "Infinity";
  }
};
 
Cookie.prototype.setMaxAge = function setMaxAge(age) {
  if (age === Infinity || age === -Infinity) {
    this.maxAge = age.toString(); // so JSON.stringify() works
  } else {
    this.maxAge = age;
  }
};
 
// gives Cookie header format
Cookie.prototype.cookieString = function cookieString() {
  var val = this.value;
  if (val == null) {
    val = '';
  }
  if (this.key === '') {
    return val;
  }
  return this.key+'='+val;
};
 
// gives Set-Cookie header format
Cookie.prototype.toString = function toString() {
  var str = this.cookieString();
 
  if (this.expires != Infinity) {
    if (this.expires instanceof Date) {
      str += '; Expires='+formatDate(this.expires);
    } else {
      str += '; Expires='+this.expires;
    }
  }
 
  if (this.maxAge != null && this.maxAge != Infinity) {
    str += '; Max-Age='+this.maxAge;
  }
 
  if (this.domain && !this.hostOnly) {
    str += '; Domain='+this.domain;
  }
  if (this.path) {
    str += '; Path='+this.path;
  }
 
  if (this.secure) {
    str += '; Secure';
  }
  if (this.httpOnly) {
    str += '; HttpOnly';
  }
  if (this.extensions) {
    this.extensions.forEach(function(ext) {
      str += '; '+ext;
    });
  }
 
  return str;
};
 
// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
// elsewhere)
// S5.3 says to give the "latest representable date" for which we use Infinity
// For "expired" we use 0
Cookie.prototype.TTL = function TTL(now) {
  /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
   * attribute, the Max-Age attribute has precedence and controls the
   * expiration date of the cookie.
   * (Concurs with S5.3 step 3)
   */
  if (this.maxAge != null) {
    return this.maxAge<=0 ? 0 : this.maxAge*1000;
  }
 
  var expires = this.expires;
  if (expires != Infinity) {
    if (!(expires instanceof Date)) {
      expires = parseDate(expires) || Infinity;
    }
 
    if (expires == Infinity) {
      return Infinity;
    }
 
    return expires.getTime() - (now || Date.now());
  }
 
  return Infinity;
};
 
// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
// elsewhere)
Cookie.prototype.expiryTime = function expiryTime(now) {
  if (this.maxAge != null) {
    var relativeTo = now || this.creation || new Date();
    var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
    return relativeTo.getTime() + age;
  }
 
  if (this.expires == Infinity) {
    return Infinity;
  }
  return this.expires.getTime();
};
 
// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
// elsewhere), except it returns a Date
Cookie.prototype.expiryDate = function expiryDate(now) {
  var millisec = this.expiryTime(now);
  if (millisec == Infinity) {
    return new Date(MAX_TIME);
  } else if (millisec == -Infinity) {
    return new Date(MIN_TIME);
  } else {
    return new Date(millisec);
  }
};
 
// This replaces the "persistent-flag" parts of S5.3 step 3
Cookie.prototype.isPersistent = function isPersistent() {
  return (this.maxAge != null || this.expires != Infinity);
};
 
// Mostly S5.1.2 and S5.2.3:
Cookie.prototype.cdomain =
Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
  if (this.domain == null) {
    return null;
  }
  return canonicalDomain(this.domain);
};
 
function CookieJar(store, options) {
  Iif (typeof options === "boolean") {
    options = {rejectPublicSuffixes: options};
  } else Iif (options == null) {
    options = {};
  }
  Iif (options.rejectPublicSuffixes != null) {
    this.rejectPublicSuffixes = options.rejectPublicSuffixes;
  }
  Eif (options.looseMode != null) {
    this.enableLooseMode = options.looseMode;
  }
 
  Eif (!store) {
    store = new MemoryCookieStore();
  }
  this.store = store;
}
CookieJar.prototype.store = null;
CookieJar.prototype.rejectPublicSuffixes = true;
CookieJar.prototype.enableLooseMode = false;
var CAN_BE_SYNC = [];
 
CAN_BE_SYNC.push('setCookie');
CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
  var err;
  var context = getCookieContext(url);
  if (options instanceof Function) {
    cb = options;
    options = {};
  }
 
  var host = canonicalDomain(context.hostname);
  var loose = this.enableLooseMode;
  if (options.loose != null) {
    loose = options.loose;
  }
 
  // S5.3 step 1
  if (!(cookie instanceof Cookie)) {
    cookie = Cookie.parse(cookie, { loose: loose });
  }
  if (!cookie) {
    err = new Error("Cookie failed to parse");
    return cb(options.ignoreError ? null : err);
  }
 
  // S5.3 step 2
  var now = options.now || new Date(); // will assign later to save effort in the face of errors
 
  // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
 
  // S5.3 step 4: NOOP; domain is null by default
 
  // S5.3 step 5: public suffixes
  if (this.rejectPublicSuffixes && cookie.domain) {
    var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
    if (suffix == null) { // e.g. "com"
      err = new Error("Cookie has domain set to a public suffix");
      return cb(options.ignoreError ? null : err);
    }
  }
 
  // S5.3 step 6:
  if (cookie.domain) {
    if (!domainMatch(host, cookie.cdomain(), false)) {
      err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
      return cb(options.ignoreError ? null : err);
    }
 
    if (cookie.hostOnly == null) { // don't reset if already set
      cookie.hostOnly = false;
    }
 
  } else {
    cookie.hostOnly = true;
    cookie.domain = host;
  }
 
  //S5.2.4 If the attribute-value is empty or if the first character of the
  //attribute-value is not %x2F ("/"):
  //Let cookie-path be the default-path.
  if (!cookie.path || cookie.path[0] !== '/') {
    cookie.path = defaultPath(context.pathname);
    cookie.pathIsDefault = true;
  }
 
  // S5.3 step 8: NOOP; secure attribute
  // S5.3 step 9: NOOP; httpOnly attribute
 
  // S5.3 step 10
  if (options.http === false && cookie.httpOnly) {
    err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
    return cb(options.ignoreError ? null : err);
  }
 
  var store = this.store;
 
  if (!store.updateCookie) {
    store.updateCookie = function(oldCookie, newCookie, cb) {
      this.putCookie(newCookie, cb);
    };
  }
 
  function withCookie(err, oldCookie) {
    if (err) {
      return cb(err);
    }
 
    var next = function(err) {
      if (err) {
        return cb(err);
      } else {
        cb(null, cookie);
      }
    };
 
    if (oldCookie) {
      // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
      // domain, and path as the newly created cookie:"
      if (options.http === false && oldCookie.httpOnly) { // step 11.2
        err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
        return cb(options.ignoreError ? null : err);
      }
      cookie.creation = oldCookie.creation; // step 11.3
      cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
      cookie.lastAccessed = now;
      // Step 11.4 (delete cookie) is implied by just setting the new one:
      store.updateCookie(oldCookie, cookie, next); // step 12
 
    } else {
      cookie.creation = cookie.lastAccessed = now;
      store.putCookie(cookie, next); // step 12
    }
  }
 
  store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
};
 
// RFC6365 S5.4
CAN_BE_SYNC.push('getCookies');
CookieJar.prototype.getCookies = function(url, options, cb) {
  var context = getCookieContext(url);
  if (options instanceof Function) {
    cb = options;
    options = {};
  }
 
  var host = canonicalDomain(context.hostname);
  var path = context.pathname || '/';
 
  var secure = options.secure;
  if (secure == null && context.protocol &&
      (context.protocol == 'https:' || context.protocol == 'wss:'))
  {
    secure = true;
  }
 
  var http = options.http;
  if (http == null) {
    http = true;
  }
 
  var now = options.now || Date.now();
  var expireCheck = options.expire !== false;
  var allPaths = !!options.allPaths;
  var store = this.store;
 
  function matchingCookie(c) {
    // "Either:
    //   The cookie's host-only-flag is true and the canonicalized
    //   request-host is identical to the cookie's domain.
    // Or:
    //   The cookie's host-only-flag is false and the canonicalized
    //   request-host domain-matches the cookie's domain."
    if (c.hostOnly) {
      if (c.domain != host) {
        return false;
      }
    } else {
      if (!domainMatch(host, c.domain, false)) {
        return false;
      }
    }
 
    // "The request-uri's path path-matches the cookie's path."
    if (!allPaths && !pathMatch(path, c.path)) {
      return false;
    }
 
    // "If the cookie's secure-only-flag is true, then the request-uri's
    // scheme must denote a "secure" protocol"
    if (c.secure && !secure) {
      return false;
    }
 
    // "If the cookie's http-only-flag is true, then exclude the cookie if the
    // cookie-string is being generated for a "non-HTTP" API"
    if (c.httpOnly && !http) {
      return false;
    }
 
    // deferred from S5.3
    // non-RFC: allow retention of expired cookies by choice
    if (expireCheck && c.expiryTime() <= now) {
      store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
      return false;
    }
 
    return true;
  }
 
  store.findCookies(host, allPaths ? null : path, function(err,cookies) {
    if (err) {
      return cb(err);
    }
 
    cookies = cookies.filter(matchingCookie);
 
    // sorting of S5.4 part 2
    if (options.sort !== false) {
      cookies = cookies.sort(cookieCompare);
    }
 
    // S5.4 part 3
    var now = new Date();
    cookies.forEach(function(c) {
      c.lastAccessed = now;
    });
    // TODO persist lastAccessed
 
    cb(null,cookies);
  });
};
 
CAN_BE_SYNC.push('getCookieString');
CookieJar.prototype.getCookieString = function(/*..., cb*/) {
  var args = Array.prototype.slice.call(arguments,0);
  var cb = args.pop();
  var next = function(err,cookies) {
    if (err) {
      cb(err);
    } else {
      cb(null, cookies
        .sort(cookieCompare)
        .map(function(c){
          return c.cookieString();
        })
        .join('; '));
    }
  };
  args.push(next);
  this.getCookies.apply(this,args);
};
 
CAN_BE_SYNC.push('getSetCookieStrings');
CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
  var args = Array.prototype.slice.call(arguments,0);
  var cb = args.pop();
  var next = function(err,cookies) {
    if (err) {
      cb(err);
    } else {
      cb(null, cookies.map(function(c){
        return c.toString();
      }));
    }
  };
  args.push(next);
  this.getCookies.apply(this,args);
};
 
CAN_BE_SYNC.push('serialize');
CookieJar.prototype.serialize = function(cb) {
  var type = this.store.constructor.name;
  if (type === 'Object') {
    type = null;
  }
 
  // update README.md "Serialization Format" if you change this, please!
  var serialized = {
    // The version of tough-cookie that serialized this jar. Generally a good
    // practice since future versions can make data import decisions based on
    // known past behavior. When/if this matters, use `semver`.
    version: 'tough-cookie@'+VERSION,
 
    // add the store type, to make humans happy:
    storeType: type,
 
    // CookieJar configuration:
    rejectPublicSuffixes: !!this.rejectPublicSuffixes,
 
    // this gets filled from getAllCookies:
    cookies: []
  };
 
  if (!(this.store.getAllCookies &&
        typeof this.store.getAllCookies === 'function'))
  {
    return cb(new Error('store does not support getAllCookies and cannot be serialized'));
  }
 
  this.store.getAllCookies(function(err,cookies) {
    if (err) {
      return cb(err);
    }
 
    serialized.cookies = cookies.map(function(cookie) {
      // convert to serialized 'raw' cookies
      cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
 
      // Remove the index so new ones get assigned during deserialization
      delete cookie.creationIndex;
 
      return cookie;
    });
 
    return cb(null, serialized);
  });
};
 
// well-known name that JSON.stringify calls
CookieJar.prototype.toJSON = function() {
  return this.serializeSync();
};
 
// use the class method CookieJar.deserialize instead of calling this directly
CAN_BE_SYNC.push('_importCookies');
CookieJar.prototype._importCookies = function(serialized, cb) {
  var jar = this;
  var cookies = serialized.cookies;
  if (!cookies || !Array.isArray(cookies)) {
    return cb(new Error('serialized jar has no cookies array'));
  }
 
  function putNext(err) {
    if (err) {
      return cb(err);
    }
 
    if (!cookies.length) {
      return cb(err, jar);
    }
 
    var cookie;
    try {
      cookie = fromJSON(cookies.shift());
    } catch (e) {
      return cb(e);
    }
 
    if (cookie === null) {
      return putNext(null); // skip this cookie
    }
 
    jar.store.putCookie(cookie, putNext);
  }
 
  putNext();
};
 
CookieJar.deserialize = function(strOrObj, store, cb) {
  if (arguments.length !== 3) {
    // store is optional
    cb = store;
    store = null;
  }
 
  var serialized;
  if (typeof strOrObj === 'string') {
    serialized = jsonParse(strOrObj);
    if (serialized instanceof Error) {
      return cb(serialized);
    }
  } else {
    serialized = strOrObj;
  }
 
  var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
  jar._importCookies(serialized, function(err) {
    if (err) {
      return cb(err);
    }
    cb(null, jar);
  });
};
 
CookieJar.deserializeSync = function(strOrObj, store) {
  var serialized = typeof strOrObj === 'string' ?
    JSON.parse(strOrObj) : strOrObj;
  var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
 
  // catch this mistake early:
  if (!jar.store.synchronous) {
    throw new Error('CookieJar store is not synchronous; use async API instead.');
  }
 
  jar._importCookiesSync(serialized);
  return jar;
};
CookieJar.fromJSON = CookieJar.deserializeSync;
 
CAN_BE_SYNC.push('clone');
CookieJar.prototype.clone = function(newStore, cb) {
  if (arguments.length === 1) {
    cb = newStore;
    newStore = null;
  }
 
  this.serialize(function(err,serialized) {
    if (err) {
      return cb(err);
    }
    CookieJar.deserialize(newStore, serialized, cb);
  });
};
 
// Use a closure to provide a true imperative API for synchronous stores.
function syncWrap(method) {
  return function() {
    if (!this.store.synchronous) {
      throw new Error('CookieJar store is not synchronous; use async API instead.');
    }
 
    var args = Array.prototype.slice.call(arguments);
    var syncErr, syncResult;
    args.push(function syncCb(err, result) {
      syncErr = err;
      syncResult = result;
    });
    this[method].apply(this, args);
 
    if (syncErr) {
      throw syncErr;
    }
    return syncResult;
  };
}
 
// wrap all declared CAN_BE_SYNC methods in the sync wrapper
CAN_BE_SYNC.forEach(function(method) {
  CookieJar.prototype[method+'Sync'] = syncWrap(method);
});
 
module.exports = {
  CookieJar: CookieJar,
  Cookie: Cookie,
  Store: Store,
  MemoryCookieStore: MemoryCookieStore,
  parseDate: parseDate,
  formatDate: formatDate,
  parse: parse,
  fromJSON: fromJSON,
  domainMatch: domainMatch,
  defaultPath: defaultPath,
  pathMatch: pathMatch,
  getPublicSuffix: pubsuffix.getPublicSuffix,
  cookieCompare: cookieCompare,
  permuteDomain: require('./permuteDomain').permuteDomain,
  permutePath: permutePath,
  canonicalDomain: canonicalDomain
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/memstore.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/memstore.js

Statements: 24.68% (19 / 77)      Branches: 0% (0 / 35)      Functions: 5.88% (1 / 17)      Lines: 24.68% (19 / 77)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172                                                              1 1 1 1   1 1 1   1 1 1     1     1       1                   1                                                                                             1                     1             1             1                     1                                                    
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';
var Store = require('./store').Store;
var permuteDomain = require('./permuteDomain').permuteDomain;
var pathMatch = require('./pathMatch').pathMatch;
var util = require('util');
 
function MemoryCookieStore() {
  Store.call(this);
  this.idx = {};
}
util.inherits(MemoryCookieStore, Store);
exports.MemoryCookieStore = MemoryCookieStore;
MemoryCookieStore.prototype.idx = null;
 
// Since it's just a struct in RAM, this Store is synchronous
MemoryCookieStore.prototype.synchronous = true;
 
// force a default depth:
MemoryCookieStore.prototype.inspect = function() {
  return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
};
 
MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
  if (!this.idx[domain]) {
    return cb(null,undefined);
  }
  if (!this.idx[domain][path]) {
    return cb(null,undefined);
  }
  return cb(null,this.idx[domain][path][key]||null);
};
 
MemoryCookieStore.prototype.findCookies = function(domain, path, cb) {
  var results = [];
  if (!domain) {
    return cb(null,[]);
  }
 
  var pathMatcher;
  if (!path) {
    // null means "all paths"
    pathMatcher = function matchAll(domainIndex) {
      for (var curPath in domainIndex) {
        var pathIndex = domainIndex[curPath];
        for (var key in pathIndex) {
          results.push(pathIndex[key]);
        }
      }
    };
 
  } else {
    pathMatcher = function matchRFC(domainIndex) {
       //NOTE: we should use path-match algorithm from S5.1.4 here
       //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
       Object.keys(domainIndex).forEach(function (cookiePath) {
         if (pathMatch(path, cookiePath)) {
           var pathIndex = domainIndex[cookiePath];
 
           for (var key in pathIndex) {
             results.push(pathIndex[key]);
           }
         }
       });
     };
  }
 
  var domains = permuteDomain(domain) || [domain];
  var idx = this.idx;
  domains.forEach(function(curDomain) {
    var domainIndex = idx[curDomain];
    if (!domainIndex) {
      return;
    }
    pathMatcher(domainIndex);
  });
 
  cb(null,results);
};
 
MemoryCookieStore.prototype.putCookie = function(cookie, cb) {
  if (!this.idx[cookie.domain]) {
    this.idx[cookie.domain] = {};
  }
  if (!this.idx[cookie.domain][cookie.path]) {
    this.idx[cookie.domain][cookie.path] = {};
  }
  this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
  cb(null);
};
 
MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) {
  // updateCookie() may avoid updating cookies that are identical.  For example,
  // lastAccessed may not be important to some stores and an equality
  // comparison could exclude that field.
  this.putCookie(newCookie,cb);
};
 
MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) {
  if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
    delete this.idx[domain][path][key];
  }
  cb(null);
};
 
MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
  if (this.idx[domain]) {
    if (path) {
      delete this.idx[domain][path];
    } else {
      delete this.idx[domain];
    }
  }
  return cb(null);
};
 
MemoryCookieStore.prototype.getAllCookies = function(cb) {
  var cookies = [];
  var idx = this.idx;
 
  var domains = Object.keys(idx);
  domains.forEach(function(domain) {
    var paths = Object.keys(idx[domain]);
    paths.forEach(function(path) {
      var keys = Object.keys(idx[domain][path]);
      keys.forEach(function(key) {
        if (key !== null) {
          cookies.push(idx[domain][path][key]);
        }
      });
    });
  });
 
  // Sort by creationIndex so deserializing retains the creation order.
  // When implementing your own store, this SHOULD retain the order too
  cookies.sort(function(a,b) {
    return (a.creationIndex||0) - (b.creationIndex||0);
  });
 
  cb(null, cookies);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js

Statements: 18.18% (2 / 11)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 18.18% (2 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                                                      1                                                 1    
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";
/*
 * "A request-path path-matches a given cookie-path if at least one of the
 * following conditions holds:"
 */
function pathMatch (reqPath, cookiePath) {
  // "o  The cookie-path and the request-path are identical."
  if (cookiePath === reqPath) {
    return true;
  }
 
  var idx = reqPath.indexOf(cookiePath);
  if (idx === 0) {
    // "o  The cookie-path is a prefix of the request-path, and the last
    // character of the cookie-path is %x2F ("/")."
    if (cookiePath.substr(-1) === "/") {
      return true;
    }
 
    // " o  The cookie-path is a prefix of the request-path, and the first
    // character of the request-path that is not included in the cookie- path
    // is a %x2F ("/") character."
    if (reqPath.substr(cookiePath.length, 1) === "/") {
      return true;
    }
  }
 
  return false;
}
 
exports.pathMatch = pathMatch;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js

Statements: 18.75% (3 / 16)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 18.75% (3 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                                              1       1                                       1    
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";
var pubsuffix = require('./pubsuffix');
 
// Gives the permutation of all possible domainMatch()es of a given domain. The
// array is in shortest-to-longest order.  Handy for indexing.
function permuteDomain (domain) {
  var pubSuf = pubsuffix.getPublicSuffix(domain);
  if (!pubSuf) {
    return null;
  }
  if (pubSuf == domain) {
    return [domain];
  }
 
  var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
  var parts = prefix.split('.').reverse();
  var cur = pubSuf;
  var permutations = [cur];
  while (parts.length) {
    cur = parts.shift() + '.' + cur;
    permutations.push(cur);
  }
  return permutations;
}
 
exports.permuteDomain = permuteDomain;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js

Statements: 8.33% (3 / 36)      Branches: 0% (0 / 22)      Functions: 0% (0 / 1)      Lines: 8.33% (3 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100              1   1                                                                                                                                                                         1          
/****************************************************
 * AUTOMATICALLY GENERATED by generate-pubsuffix.js *
 *                  DO NOT EDIT!                    *
 ****************************************************/
 
"use strict";
 
var punycode = require('punycode');
 
module.exports.getPublicSuffix = function getPublicSuffix(domain) {
  /*!
   * Copyright (c) 2015, Salesforce.com, Inc.
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice,
   * this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   * this list of conditions and the following disclaimer in the documentation
   * and/or other materials provided with the distribution.
   *
   * 3. Neither the name of Salesforce.com nor the names of its contributors may
   * be used to endorse or promote products derived from this software without
   * specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   * POSSIBILITY OF SUCH DAMAGE.
   */
  if (!domain) {
    return null;
  }
  if (domain.match(/^\./)) {
    return null;
  }
  var asciiDomain = punycode.toASCII(domain);
  var converted = false;
  if (asciiDomain !== domain) {
    domain = asciiDomain;
    converted = true;
  }
  if (index[domain]) {
    return null;
  }
 
  domain = domain.toLowerCase();
  var parts = domain.split('.').reverse();
 
  var suffix = '';
  var suffixLen = 0;
  for (var i=0; i<parts.length; i++) {
    var part = parts[i];
    var starstr = '*'+suffix;
    var partstr = part+suffix;
 
    if (index[starstr]) { // star rule matches
      suffixLen = i+1;
      if (index[partstr] === false) { // exception rule matches (NB: false, not undefined)
        suffixLen--;
      }
    } else if (index[partstr]) { // exact match, not exception
      suffixLen = i+1;
    }
 
    suffix = '.'+partstr;
  }
 
  if (index['*'+suffix]) { // *.domain exists (e.g. *.kyoto.jp for domain='kyoto.jp');
    return null;
  }
 
  suffixLen = suffixLen || 1;
  if (parts.length > suffixLen) {
    var publicSuffix = parts.slice(0,suffixLen+1).reverse().join('.');
    return converted ? punycode.toUnicode(publicSuffix) : publicSuffix;
  }
 
  return null;
};
 
// The following generated structure is used under the MPL version 2.0
// See public-suffix.txt for more information
 
var index = module.exports.index = Object.freeze(
{"ac":true,"com.ac":true,"edu.ac":true,"gov.ac":true,"net.ac":true,"mil.ac":true,"org.ac":true,"ad":true,"nom.ad":true,"ae":true,"co.ae":true,"net.ae":true,"org.ae":true,"sch.ae":true,"ac.ae":true,"gov.ae":true,"mil.ae":true,"aero":true,"accident-investigation.aero":true,"accident-prevention.aero":true,"aerobatic.aero":true,"aeroclub.aero":true,"aerodrome.aero":true,"agents.aero":true,"aircraft.aero":true,"airline.aero":true,"airport.aero":true,"air-surveillance.aero":true,"airtraffic.aero":true,"air-traffic-control.aero":true,"ambulance.aero":true,"amusement.aero":true,"association.aero":true,"author.aero":true,"ballooning.aero":true,"broker.aero":true,"caa.aero":true,"cargo.aero":true,"catering.aero":true,"certification.aero":true,"championship.aero":true,"charter.aero":true,"civilaviation.aero":true,"club.aero":true,"conference.aero":true,"consultant.aero":true,"consulting.aero":true,"control.aero":true,"council.aero":true,"crew.aero":true,"design.aero":true,"dgca.aero":true,"educator.aero":true,"emergency.aero":true,"engine.aero":true,"engineer.aero":true,"entertainment.aero":true,"equipment.aero":true,"exchange.aero":true,"express.aero":true,"federation.aero":true,"flight.aero":true,"freight.aero":true,"fuel.aero":true,"gliding.aero":true,"government.aero":true,"groundhandling.aero":true,"group.aero":true,"hanggliding.aero":true,"homebuilt.aero":true,"insurance.aero":true,"journal.aero":true,"journalist.aero":true,"leasing.aero":true,"logistics.aero":true,"magazine.aero":true,"maintenance.aero":true,"marketplace.aero":true,"media.aero":true,"microlight.aero":true,"modelling.aero":true,"navigation.aero":true,"parachuting.aero":true,"paragliding.aero":true,"passenger-association.aero":true,"pilot.aero":true,"press.aero":true,"production.aero":true,"recreation.aero":true,"repbody.aero":true,"res.aero":true,"research.aero":true,"rotorcraft.aero":true,"safety.aero":true,"scientist.aero":true,"services.aero":true,"show.aero":true,"skydiving.aero":true,"software.aero":true,"student.aero":true,"taxi.aero":true,"trader.aero":true,"trading.aero":true,"trainer.aero":true,"union.aero":true,"workinggroup.aero":true,"works.aero":true,"af":true,"gov.af":true,"com.af":true,"org.af":true,"net.af":true,"edu.af":true,"ag":true,"com.ag":true,"org.ag":true,"net.ag":true,"co.ag":true,"nom.ag":true,"ai":true,"off.ai":true,"com.ai":true,"net.ai":true,"org.ai":true,"al":true,"com.al":true,"edu.al":true,"gov.al":true,"mil.al":true,"net.al":true,"org.al":true,"am":true,"an":true,"com.an":true,"net.an":true,"org.an":true,"edu.an":true,"ao":true,"ed.ao":true,"gv.ao":true,"og.ao":true,"co.ao":true,"pb.ao":true,"it.ao":true,"aq":true,"ar":true,"com.ar":true,"edu.ar":true,"gob.ar":true,"gov.ar":true,"int.ar":true,"mil.ar":true,"net.ar":true,"org.ar":true,"tur.ar":true,"arpa":true,"e164.arpa":true,"in-addr.arpa":true,"ip6.arpa":true,"iris.arpa":true,"uri.arpa":true,"urn.arpa":true,"as":true,"gov.as":true,"asia":true,"at":true,"ac.at":true,"co.at":true,"gv.at":true,"or.at":true,"au":true,"com.au":true,"net.au":true,"org.au":true,"edu.au":true,"gov.au":true,"asn.au":true,"id.au":true,"info.au":true,"conf.au":true,"oz.au":true,"act.au":true,"nsw.au":true,"nt.au":true,"qld.au":true,"sa.au":true,"tas.au":true,"vic.au":true,"wa.au":true,"act.edu.au":true,"nsw.edu.au":true,"nt.edu.au":true,"qld.edu.au":true,"sa.edu.au":true,"tas.edu.au":true,"vic.edu.au":true,"wa.edu.au":true,"qld.gov.au":true,"sa.gov.au":true,"tas.gov.au":true,"vic.gov.au":true,"wa.gov.au":true,"aw":true,"com.aw":true,"ax":true,"az":true,"com.az":true,"net.az":true,"int.az":true,"gov.az":true,"org.az":true,"edu.az":true,"info.az":true,"pp.az":true,"mil.az":true,"name.az":true,"pro.az":true,"biz.az":true,"ba":true,"org.ba":true,"net.ba":true,"edu.ba":true,"gov.ba":true,"mil.ba":true,"unsa.ba":true,"unbi.ba":true,"co.ba":true,"com.ba":true,"rs.ba":true,"bb":true,"biz.bb":true,"co.bb":true,"com.bb":true,"edu.bb":true,"gov.bb":true,"info.bb":true,"net.bb":true,"org.bb":true,"store.bb":true,"tv.bb":true,"*.bd":true,"be":true,"ac.be":true,"bf":true,"gov.bf":true,"bg":true,"a.bg":true,"b.bg":true,"c.bg":true,"d.bg":true,"e.bg":true,"f.bg":true,"g.bg":true,"h.bg":true,"i.bg":true,"j.bg":true,"k.bg":true,"l.bg":true,"m.bg":true,"n.bg":true,"o.bg":true,"p.bg":true,"q.bg":true,"r.bg":true,"s.bg":true,"t.bg":true,"u.bg":true,"v.bg":true,"w.bg":true,"x.bg":true,"y.bg":true,"z.bg":true,"0.bg":true,"1.bg":true,"2.bg":true,"3.bg":true,"4.bg":true,"5.bg":true,"6.bg":true,"7.bg":true,"8.bg":true,"9.bg":true,"bh":true,"com.bh":true,"edu.bh":true,"net.bh":true,"org.bh":true,"gov.bh":true,"bi":true,"co.bi":true,"com.bi":true,"edu.bi":true,"or.bi":true,"org.bi":true,"biz":true,"bj":true,"asso.bj":true,"barreau.bj":true,"gouv.bj":true,"bm":true,"com.bm":true,"edu.bm":true,"gov.bm":true,"net.bm":true,"org.bm":true,"*.bn":true,"bo":true,"com.bo":true,"edu.bo":true,"gov.bo":true,"gob.bo":true,"int.bo":true,"org.bo":true,"net.bo":true,"mil.bo":true,"tv.bo":true,"br":true,"adm.br":true,"adv.br":true,"agr.br":true,"am.br":true,"arq.br":true,"art.br":true,"ato.br":true,"b.br":true,"bio.br":true,"blog.br":true,"bmd.br":true,"cim.br":true,"cng.br":true,"cnt.br":true,"com.br":true,"coop.br":true,"ecn.br":true,"eco.br":true,"edu.br":true,"emp.br":true,"eng.br":true,"esp.br":true,"etc.br":true,"eti.br":true,"far.br":true,"flog.br":true,"fm.br":true,"fnd.br":true,"fot.br":true,"fst.br":true,"g12.br":true,"ggf.br":true,"gov.br":true,"imb.br":true,"ind.br":true,"inf.br":true,"jor.br":true,"jus.br":true,"leg.br":true,"lel.br":true,"mat.br":true,"med.br":true,"mil.br":true,"mp.br":true,"mus.br":true,"net.br":true,"*.nom.br":true,"not.br":true,"ntr.br":true,"odo.br":true,"org.br":true,"ppg.br":true,"pro.br":true,"psc.br":true,"psi.br":true,"qsl.br":true,"radio.br":true,"rec.br":true,"slg.br":true,"srv.br":true,"taxi.br":true,"teo.br":true,"tmp.br":true,"trd.br":true,"tur.br":true,"tv.br":true,"vet.br":true,"vlog.br":true,"wiki.br":true,"zlg.br":true,"bs":true,"com.bs":true,"net.bs":true,"org.bs":true,"edu.bs":true,"gov.bs":true,"bt":true,"com.bt":true,"edu.bt":true,"gov.bt":true,"net.bt":true,"org.bt":true,"bv":true,"bw":true,"co.bw":true,"org.bw":true,"by":true,"gov.by":true,"mil.by":true,"com.by":true,"of.by":true,"bz":true,"com.bz":true,"net.bz":true,"org.bz":true,"edu.bz":true,"gov.bz":true,"ca":true,"ab.ca":true,"bc.ca":true,"mb.ca":true,"nb.ca":true,"nf.ca":true,"nl.ca":true,"ns.ca":true,"nt.ca":true,"nu.ca":true,"on.ca":true,"pe.ca":true,"qc.ca":true,"sk.ca":true,"yk.ca":true,"gc.ca":true,"cat":true,"cc":true,"cd":true,"gov.cd":true,"cf":true,"cg":true,"ch":true,"ci":true,"org.ci":true,"or.ci":true,"com.ci":true,"co.ci":true,"edu.ci":true,"ed.ci":true,"ac.ci":true,"net.ci":true,"go.ci":true,"asso.ci":true,"xn--aroport-bya.ci":true,"int.ci":true,"presse.ci":true,"md.ci":true,"gouv.ci":true,"*.ck":true,"www.ck":false,"cl":true,"gov.cl":true,"gob.cl":true,"co.cl":true,"mil.cl":true,"cm":true,"co.cm":true,"com.cm":true,"gov.cm":true,"net.cm":true,"cn":true,"ac.cn":true,"com.cn":true,"edu.cn":true,"gov.cn":true,"net.cn":true,"org.cn":true,"mil.cn":true,"xn--55qx5d.cn":true,"xn--io0a7i.cn":true,"xn--od0alg.cn":true,"ah.cn":true,"bj.cn":true,"cq.cn":true,"fj.cn":true,"gd.cn":true,"gs.cn":true,"gz.cn":true,"gx.cn":true,"ha.cn":true,"hb.cn":true,"he.cn":true,"hi.cn":true,"hl.cn":true,"hn.cn":true,"jl.cn":true,"js.cn":true,"jx.cn":true,"ln.cn":true,"nm.cn":true,"nx.cn":true,"qh.cn":true,"sc.cn":true,"sd.cn":true,"sh.cn":true,"sn.cn":true,"sx.cn":true,"tj.cn":true,"xj.cn":true,"xz.cn":true,"yn.cn":true,"zj.cn":true,"hk.cn":true,"mo.cn":true,"tw.cn":true,"co":true,"arts.co":true,"com.co":true,"edu.co":true,"firm.co":true,"gov.co":true,"info.co":true,"int.co":true,"mil.co":true,"net.co":true,"nom.co":true,"org.co":true,"rec.co":true,"web.co":true,"com":true,"coop":true,"cr":true,"ac.cr":true,"co.cr":true,"ed.cr":true,"fi.cr":true,"go.cr":true,"or.cr":true,"sa.cr":true,"cu":true,"com.cu":true,"edu.cu":true,"org.cu":true,"net.cu":true,"gov.cu":true,"inf.cu":true,"cv":true,"cw":true,"com.cw":true,"edu.cw":true,"net.cw":true,"org.cw":true,"cx":true,"gov.cx":true,"ac.cy":true,"biz.cy":true,"com.cy":true,"ekloges.cy":true,"gov.cy":true,"ltd.cy":true,"name.cy":true,"net.cy":true,"org.cy":true,"parliament.cy":true,"press.cy":true,"pro.cy":true,"tm.cy":true,"cz":true,"de":true,"dj":true,"dk":true,"dm":true,"com.dm":true,"net.dm":true,"org.dm":true,"edu.dm":true,"gov.dm":true,"do":true,"art.do":true,"com.do":true,"edu.do":true,"gob.do":true,"gov.do":true,"mil.do":true,"net.do":true,"org.do":true,"sld.do":true,"web.do":true,"dz":true,"com.dz":true,"org.dz":true,"net.dz":true,"gov.dz":true,"edu.dz":true,"asso.dz":true,"pol.dz":true,"art.dz":true,"ec":true,"com.ec":true,"info.ec":true,"net.ec":true,"fin.ec":true,"k12.ec":true,"med.ec":true,"pro.ec":true,"org.ec":true,"edu.ec":true,"gov.ec":true,"gob.ec":true,"mil.ec":true,"edu":true,"ee":true,"edu.ee":true,"gov.ee":true,"riik.ee":true,"lib.ee":true,"med.ee":true,"com.ee":true,"pri.ee":true,"aip.ee":true,"org.ee":true,"fie.ee":true,"eg":true,"com.eg":true,"edu.eg":true,"eun.eg":true,"gov.eg":true,"mil.eg":true,"name.eg":true,"net.eg":true,"org.eg":true,"sci.eg":true,"*.er":true,"es":true,"com.es":true,"nom.es":true,"org.es":true,"gob.es":true,"edu.es":true,"et":true,"com.et":true,"gov.et":true,"org.et":true,"edu.et":true,"biz.et":true,"name.et":true,"info.et":true,"net.et":true,"eu":true,"fi":true,"aland.fi":true,"*.fj":true,"*.fk":true,"fm":true,"fo":true,"fr":true,"com.fr":true,"asso.fr":true,"nom.fr":true,"prd.fr":true,"presse.fr":true,"tm.fr":true,"aeroport.fr":true,"assedic.fr":true,"avocat.fr":true,"avoues.fr":true,"cci.fr":true,"chambagri.fr":true,"chirurgiens-dentistes.fr":true,"experts-comptables.fr":true,"geometre-expert.fr":true,"gouv.fr":true,"greta.fr":true,"huissier-justice.fr":true,"medecin.fr":true,"notaires.fr":true,"pharmacien.fr":true,"port.fr":true,"veterinaire.fr":true,"ga":true,"gb":true,"gd":true,"ge":true,"com.ge":true,"edu.ge":true,"gov.ge":true,"org.ge":true,"mil.ge":true,"net.ge":true,"pvt.ge":true,"gf":true,"gg":true,"co.gg":true,"net.gg":true,"org.gg":true,"gh":true,"com.gh":true,"edu.gh":true,"gov.gh":true,"org.gh":true,"mil.gh":true,"gi":true,"com.gi":true,"ltd.gi":true,"gov.gi":true,"mod.gi":true,"edu.gi":true,"org.gi":true,"gl":true,"co.gl":true,"com.gl":true,"edu.gl":true,"net.gl":true,"org.gl":true,"gm":true,"gn":true,"ac.gn":true,"com.gn":true,"edu.gn":true,"gov.gn":true,"org.gn":true,"net.gn":true,"gov":true,"gp":true,"com.gp":true,"net.gp":true,"mobi.gp":true,"edu.gp":true,"org.gp":true,"asso.gp":true,"gq":true,"gr":true,"com.gr":true,"edu.gr":true,"net.gr":true,"org.gr":true,"gov.gr":true,"gs":true,"gt":true,"com.gt":true,"edu.gt":true,"gob.gt":true,"ind.gt":true,"mil.gt":true,"net.gt":true,"org.gt":true,"*.gu":true,"gw":true,"gy":true,"co.gy":true,"com.gy":true,"net.gy":true,"hk":true,"com.hk":true,"edu.hk":true,"gov.hk":true,"idv.hk":true,"net.hk":true,"org.hk":true,"xn--55qx5d.hk":true,"xn--wcvs22d.hk":true,"xn--lcvr32d.hk":true,"xn--mxtq1m.hk":true,"xn--gmqw5a.hk":true,"xn--ciqpn.hk":true,"xn--gmq050i.hk":true,"xn--zf0avx.hk":true,"xn--io0a7i.hk":true,"xn--mk0axi.hk":true,"xn--od0alg.hk":true,"xn--od0aq3b.hk":true,"xn--tn0ag.hk":true,"xn--uc0atv.hk":true,"xn--uc0ay4a.hk":true,"hm":true,"hn":true,"com.hn":true,"edu.hn":true,"org.hn":true,"net.hn":true,"mil.hn":true,"gob.hn":true,"hr":true,"iz.hr":true,"from.hr":true,"name.hr":true,"com.hr":true,"ht":true,"com.ht":true,"shop.ht":true,"firm.ht":true,"info.ht":true,"adult.ht":true,"net.ht":true,"pro.ht":true,"org.ht":true,"med.ht":true,"art.ht":true,"coop.ht":true,"pol.ht":true,"asso.ht":true,"edu.ht":true,"rel.ht":true,"gouv.ht":true,"perso.ht":true,"hu":true,"co.hu":true,"info.hu":true,"org.hu":true,"priv.hu":true,"sport.hu":true,"tm.hu":true,"2000.hu":true,"agrar.hu":true,"bolt.hu":true,"casino.hu":true,"city.hu":true,"erotica.hu":true,"erotika.hu":true,"film.hu":true,"forum.hu":true,"games.hu":true,"hotel.hu":true,"ingatlan.hu":true,"jogasz.hu":true,"konyvelo.hu":true,"lakas.hu":true,"media.hu":true,"news.hu":true,"reklam.hu":true,"sex.hu":true,"shop.hu":true,"suli.hu":true,"szex.hu":true,"tozsde.hu":true,"utazas.hu":true,"video.hu":true,"id":true,"ac.id":true,"biz.id":true,"co.id":true,"desa.id":true,"go.id":true,"mil.id":true,"my.id":true,"net.id":true,"or.id":true,"sch.id":true,"web.id":true,"ie":true,"gov.ie":true,"il":true,"ac.il":true,"co.il":true,"gov.il":true,"idf.il":true,"k12.il":true,"muni.il":true,"net.il":true,"org.il":true,"im":true,"ac.im":true,"co.im":true,"com.im":true,"ltd.co.im":true,"net.im":true,"org.im":true,"plc.co.im":true,"tt.im":true,"tv.im":true,"in":true,"co.in":true,"firm.in":true,"net.in":true,"org.in":true,"gen.in":true,"ind.in":true,"nic.in":true,"ac.in":true,"edu.in":true,"res.in":true,"gov.in":true,"mil.in":true,"info":true,"int":true,"eu.int":true,"io":true,"com.io":true,"iq":true,"gov.iq":true,"edu.iq":true,"mil.iq":true,"com.iq":true,"org.iq":true,"net.iq":true,"ir":true,"ac.ir":true,"co.ir":true,"gov.ir":true,"id.ir":true,"net.ir":true,"org.ir":true,"sch.ir":true,"xn--mgba3a4f16a.ir":true,"xn--mgba3a4fra.ir":true,"is":true,"net.is":true,"com.is":true,"edu.is":true,"gov.is":true,"org.is":true,"int.is":true,"it":true,"gov.it":true,"edu.it":true,"abr.it":true,"abruzzo.it":true,"aosta-valley.it":true,"aostavalley.it":true,"bas.it":true,"basilicata.it":true,"cal.it":true,"calabria.it":true,"cam.it":true,"campania.it":true,"emilia-romagna.it":true,"emiliaromagna.it":true,"emr.it":true,"friuli-v-giulia.it":true,"friuli-ve-giulia.it":true,"friuli-vegiulia.it":true,"friuli-venezia-giulia.it":true,"friuli-veneziagiulia.it":true,"friuli-vgiulia.it":true,"friuliv-giulia.it":true,"friulive-giulia.it":true,"friulivegiulia.it":true,"friulivenezia-giulia.it":true,"friuliveneziagiulia.it":true,"friulivgiulia.it":true,"fvg.it":true,"laz.it":true,"lazio.it":true,"lig.it":true,"liguria.it":true,"lom.it":true,"lombardia.it":true,"lombardy.it":true,"lucania.it":true,"mar.it":true,"marche.it":true,"mol.it":true,"molise.it":true,"piedmont.it":true,"piemonte.it":true,"pmn.it":true,"pug.it":true,"puglia.it":true,"sar.it":true,"sardegna.it":true,"sardinia.it":true,"sic.it":true,"sicilia.it":true,"sicily.it":true,"taa.it":true,"tos.it":true,"toscana.it":true,"trentino-a-adige.it":true,"trentino-aadige.it":true,"trentino-alto-adige.it":true,"trentino-altoadige.it":true,"trentino-s-tirol.it":true,"trentino-stirol.it":true,"trentino-sud-tirol.it":true,"trentino-sudtirol.it":true,"trentino-sued-tirol.it":true,"trentino-suedtirol.it":true,"trentinoa-adige.it":true,"trentinoaadige.it":true,"trentinoalto-adige.it":true,"trentinoaltoadige.it":true,"trentinos-tirol.it":true,"trentinostirol.it":true,"trentinosud-tirol.it":true,"trentinosudtirol.it":true,"trentinosued-tirol.it":true,"trentinosuedtirol.it":true,"tuscany.it":true,"umb.it":true,"umbria.it":true,"val-d-aosta.it":true,"val-daosta.it":true,"vald-aosta.it":true,"valdaosta.it":true,"valle-aosta.it":true,"valle-d-aosta.it":true,"valle-daosta.it":true,"valleaosta.it":true,"valled-aosta.it":true,"valledaosta.it":true,"vallee-aoste.it":true,"valleeaoste.it":true,"vao.it":true,"vda.it":true,"ven.it":true,"veneto.it":true,"ag.it":true,"agrigento.it":true,"al.it":true,"alessandria.it":true,"alto-adige.it":true,"altoadige.it":true,"an.it":true,"ancona.it":true,"andria-barletta-trani.it":true,"andria-trani-barletta.it":true,"andriabarlettatrani.it":true,"andriatranibarletta.it":true,"ao.it":true,"aosta.it":true,"aoste.it":true,"ap.it":true,"aq.it":true,"aquila.it":true,"ar.it":true,"arezzo.it":true,"ascoli-piceno.it":true,"ascolipiceno.it":true,"asti.it":true,"at.it":true,"av.it":true,"avellino.it":true,"ba.it":true,"balsan.it":true,"bari.it":true,"barletta-trani-andria.it":true,"barlettatraniandria.it":true,"belluno.it":true,"benevento.it":true,"bergamo.it":true,"bg.it":true,"bi.it":true,"biella.it":true,"bl.it":true,"bn.it":true,"bo.it":true,"bologna.it":true,"bolzano.it":true,"bozen.it":true,"br.it":true,"brescia.it":true,"brindisi.it":true,"bs.it":true,"bt.it":true,"bz.it":true,"ca.it":true,"cagliari.it":true,"caltanissetta.it":true,"campidano-medio.it":true,"campidanomedio.it":true,"campobasso.it":true,"carbonia-iglesias.it":true,"carboniaiglesias.it":true,"carrara-massa.it":true,"carraramassa.it":true,"caserta.it":true,"catania.it":true,"catanzaro.it":true,"cb.it":true,"ce.it":true,"cesena-forli.it":true,"cesenaforli.it":true,"ch.it":true,"chieti.it":true,"ci.it":true,"cl.it":true,"cn.it":true,"co.it":true,"como.it":true,"cosenza.it":true,"cr.it":true,"cremona.it":true,"crotone.it":true,"cs.it":true,"ct.it":true,"cuneo.it":true,"cz.it":true,"dell-ogliastra.it":true,"dellogliastra.it":true,"en.it":true,"enna.it":true,"fc.it":true,"fe.it":true,"fermo.it":true,"ferrara.it":true,"fg.it":true,"fi.it":true,"firenze.it":true,"florence.it":true,"fm.it":true,"foggia.it":true,"forli-cesena.it":true,"forlicesena.it":true,"fr.it":true,"frosinone.it":true,"ge.it":true,"genoa.it":true,"genova.it":true,"go.it":true,"gorizia.it":true,"gr.it":true,"grosseto.it":true,"iglesias-carbonia.it":true,"iglesiascarbonia.it":true,"im.it":true,"imperia.it":true,"is.it":true,"isernia.it":true,"kr.it":true,"la-spezia.it":true,"laquila.it":true,"laspezia.it":true,"latina.it":true,"lc.it":true,"le.it":true,"lecce.it":true,"lecco.it":true,"li.it":true,"livorno.it":true,"lo.it":true,"lodi.it":true,"lt.it":true,"lu.it":true,"lucca.it":true,"macerata.it":true,"mantova.it":true,"massa-carrara.it":true,"massacarrara.it":true,"matera.it":true,"mb.it":true,"mc.it":true,"me.it":true,"medio-campidano.it":true,"mediocampidano.it":true,"messina.it":true,"mi.it":true,"milan.it":true,"milano.it":true,"mn.it":true,"mo.it":true,"modena.it":true,"monza-brianza.it":true,"monza-e-della-brianza.it":true,"monza.it":true,"monzabrianza.it":true,"monzaebrianza.it":true,"monzaedellabrianza.it":true,"ms.it":true,"mt.it":true,"na.it":true,"naples.it":true,"napoli.it":true,"no.it":true,"novara.it":true,"nu.it":true,"nuoro.it":true,"og.it":true,"ogliastra.it":true,"olbia-tempio.it":true,"olbiatempio.it":true,"or.it":true,"oristano.it":true,"ot.it":true,"pa.it":true,"padova.it":true,"padua.it":true,"palermo.it":true,"parma.it":true,"pavia.it":true,"pc.it":true,"pd.it":true,"pe.it":true,"perugia.it":true,"pesaro-urbino.it":true,"pesarourbino.it":true,"pescara.it":true,"pg.it":true,"pi.it":true,"piacenza.it":true,"pisa.it":true,"pistoia.it":true,"pn.it":true,"po.it":true,"pordenone.it":true,"potenza.it":true,"pr.it":true,"prato.it":true,"pt.it":true,"pu.it":true,"pv.it":true,"pz.it":true,"ra.it":true,"ragusa.it":true,"ravenna.it":true,"rc.it":true,"re.it":true,"reggio-calabria.it":true,"reggio-emilia.it":true,"reggiocalabria.it":true,"reggioemilia.it":true,"rg.it":true,"ri.it":true,"rieti.it":true,"rimini.it":true,"rm.it":true,"rn.it":true,"ro.it":true,"roma.it":true,"rome.it":true,"rovigo.it":true,"sa.it":true,"salerno.it":true,"sassari.it":true,"savona.it":true,"si.it":true,"siena.it":true,"siracusa.it":true,"so.it":true,"sondrio.it":true,"sp.it":true,"sr.it":true,"ss.it":true,"suedtirol.it":true,"sv.it":true,"ta.it":true,"taranto.it":true,"te.it":true,"tempio-olbia.it":true,"tempioolbia.it":true,"teramo.it":true,"terni.it":true,"tn.it":true,"to.it":true,"torino.it":true,"tp.it":true,"tr.it":true,"trani-andria-barletta.it":true,"trani-barletta-andria.it":true,"traniandriabarletta.it":true,"tranibarlettaandria.it":true,"trapani.it":true,"trentino.it":true,"trento.it":true,"treviso.it":true,"trieste.it":true,"ts.it":true,"turin.it":true,"tv.it":true,"ud.it":true,"udine.it":true,"urbino-pesaro.it":true,"urbinopesaro.it":true,"va.it":true,"varese.it":true,"vb.it":true,"vc.it":true,"ve.it":true,"venezia.it":true,"venice.it":true,"verbania.it":true,"vercelli.it":true,"verona.it":true,"vi.it":true,"vibo-valentia.it":true,"vibovalentia.it":true,"vicenza.it":true,"viterbo.it":true,"vr.it":true,"vs.it":true,"vt.it":true,"vv.it":true,"je":true,"co.je":true,"net.je":true,"org.je":true,"*.jm":true,"jo":true,"com.jo":true,"org.jo":true,"net.jo":true,"edu.jo":true,"sch.jo":true,"gov.jo":true,"mil.jo":true,"name.jo":true,"jobs":true,"jp":true,"ac.jp":true,"ad.jp":true,"co.jp":true,"ed.jp":true,"go.jp":true,"gr.jp":true,"lg.jp":true,"ne.jp":true,"or.jp":true,"aichi.jp":true,"akita.jp":true,"aomori.jp":true,"chiba.jp":true,"ehime.jp":true,"fukui.jp":true,"fukuoka.jp":true,"fukushima.jp":true,"gifu.jp":true,"gunma.jp":true,"hiroshima.jp":true,"hokkaido.jp":true,"hyogo.jp":true,"ibaraki.jp":true,"ishikawa.jp":true,"iwate.jp":true,"kagawa.jp":true,"kagoshima.jp":true,"kanagawa.jp":true,"kochi.jp":true,"kumamoto.jp":true,"kyoto.jp":true,"mie.jp":true,"miyagi.jp":true,"miyazaki.jp":true,"nagano.jp":true,"nagasaki.jp":true,"nara.jp":true,"niigata.jp":true,"oita.jp":true,"okayama.jp":true,"okinawa.jp":true,"osaka.jp":true,"saga.jp":true,"saitama.jp":true,"shiga.jp":true,"shimane.jp":true,"shizuoka.jp":true,"tochigi.jp":true,"tokushima.jp":true,"tokyo.jp":true,"tottori.jp":true,"toyama.jp":true,"wakayama.jp":true,"yamagata.jp":true,"yamaguchi.jp":true,"yamanashi.jp":true,"xn--4pvxs.jp":true,"xn--vgu402c.jp":true,"xn--c3s14m.jp":true,"xn--f6qx53a.jp":true,"xn--8pvr4u.jp":true,"xn--uist22h.jp":true,"xn--djrs72d6uy.jp":true,"xn--mkru45i.jp":true,"xn--0trq7p7nn.jp":true,"xn--8ltr62k.jp":true,"xn--2m4a15e.jp":true,"xn--efvn9s.jp":true,"xn--32vp30h.jp":true,"xn--4it797k.jp":true,"xn--1lqs71d.jp":true,"xn--5rtp49c.jp":true,"xn--5js045d.jp":true,"xn--ehqz56n.jp":true,"xn--1lqs03n.jp":true,"xn--qqqt11m.jp":true,"xn--kbrq7o.jp":true,"xn--pssu33l.jp":true,"xn--ntsq17g.jp":true,"xn--uisz3g.jp":true,"xn--6btw5a.jp":true,"xn--1ctwo.jp":true,"xn--6orx2r.jp":true,"xn--rht61e.jp":true,"xn--rht27z.jp":true,"xn--djty4k.jp":true,"xn--nit225k.jp":true,"xn--rht3d.jp":true,"xn--klty5x.jp":true,"xn--kltx9a.jp":true,"xn--kltp7d.jp":true,"xn--uuwu58a.jp":true,"xn--zbx025d.jp":true,"xn--ntso0iqx3a.jp":true,"xn--elqq16h.jp":true,"xn--4it168d.jp":true,"xn--klt787d.jp":true,"xn--rny31h.jp":true,"xn--7t0a264c.jp":true,"xn--5rtq34k.jp":true,"xn--k7yn95e.jp":true,"xn--tor131o.jp":true,"xn--d5qv7z876c.jp":true,"*.kawasaki.jp":true,"*.kitakyushu.jp":true,"*.kobe.jp":true,"*.nagoya.jp":true,"*.sapporo.jp":true,"*.sendai.jp":true,"*.yokohama.jp":true,"city.kawasaki.jp":false,"city.kitakyushu.jp":false,"city.kobe.jp":false,"city.nagoya.jp":false,"city.sapporo.jp":false,"city.sendai.jp":false,"city.yokohama.jp":false,"aisai.aichi.jp":true,"ama.aichi.jp":true,"anjo.aichi.jp":true,"asuke.aichi.jp":true,"chiryu.aichi.jp":true,"chita.aichi.jp":true,"fuso.aichi.jp":true,"gamagori.aichi.jp":true,"handa.aichi.jp":true,"hazu.aichi.jp":true,"hekinan.aichi.jp":true,"higashiura.aichi.jp":true,"ichinomiya.aichi.jp":true,"inazawa.aichi.jp":true,"inuyama.aichi.jp":true,"isshiki.aichi.jp":true,"iwakura.aichi.jp":true,"kanie.aichi.jp":true,"kariya.aichi.jp":true,"kasugai.aichi.jp":true,"kira.aichi.jp":true,"kiyosu.aichi.jp":true,"komaki.aichi.jp":true,"konan.aichi.jp":true,"kota.aichi.jp":true,"mihama.aichi.jp":true,"miyoshi.aichi.jp":true,"nishio.aichi.jp":true,"nisshin.aichi.jp":true,"obu.aichi.jp":true,"oguchi.aichi.jp":true,"oharu.aichi.jp":true,"okazaki.aichi.jp":true,"owariasahi.aichi.jp":true,"seto.aichi.jp":true,"shikatsu.aichi.jp":true,"shinshiro.aichi.jp":true,"shitara.aichi.jp":true,"tahara.aichi.jp":true,"takahama.aichi.jp":true,"tobishima.aichi.jp":true,"toei.aichi.jp":true,"togo.aichi.jp":true,"tokai.aichi.jp":true,"tokoname.aichi.jp":true,"toyoake.aichi.jp":true,"toyohashi.aichi.jp":true,"toyokawa.aichi.jp":true,"toyone.aichi.jp":true,"toyota.aichi.jp":true,"tsushima.aichi.jp":true,"yatomi.aichi.jp":true,"akita.akita.jp":true,"daisen.akita.jp":true,"fujisato.akita.jp":true,"gojome.akita.jp":true,"hachirogata.akita.jp":true,"happou.akita.jp":true,"higashinaruse.akita.jp":true,"honjo.akita.jp":true,"honjyo.akita.jp":true,"ikawa.akita.jp":true,"kamikoani.akita.jp":true,"kamioka.akita.jp":true,"katagami.akita.jp":true,"kazuno.akita.jp":true,"kitaakita.akita.jp":true,"kosaka.akita.jp":true,"kyowa.akita.jp":true,"misato.akita.jp":true,"mitane.akita.jp":true,"moriyoshi.akita.jp":true,"nikaho.akita.jp":true,"noshiro.akita.jp":true,"odate.akita.jp":true,"oga.akita.jp":true,"ogata.akita.jp":true,"semboku.akita.jp":true,"yokote.akita.jp":true,"yurihonjo.akita.jp":true,"aomori.aomori.jp":true,"gonohe.aomori.jp":true,"hachinohe.aomori.jp":true,"hashikami.aomori.jp":true,"hiranai.aomori.jp":true,"hirosaki.aomori.jp":true,"itayanagi.aomori.jp":true,"kuroishi.aomori.jp":true,"misawa.aomori.jp":true,"mutsu.aomori.jp":true,"nakadomari.aomori.jp":true,"noheji.aomori.jp":true,"oirase.aomori.jp":true,"owani.aomori.jp":true,"rokunohe.aomori.jp":true,"sannohe.aomori.jp":true,"shichinohe.aomori.jp":true,"shingo.aomori.jp":true,"takko.aomori.jp":true,"towada.aomori.jp":true,"tsugaru.aomori.jp":true,"tsuruta.aomori.jp":true,"abiko.chiba.jp":true,"asahi.chiba.jp":true,"chonan.chiba.jp":true,"chosei.chiba.jp":true,"choshi.chiba.jp":true,"chuo.chiba.jp":true,"funabashi.chiba.jp":true,"futtsu.chiba.jp":true,"hanamigawa.chiba.jp":true,"ichihara.chiba.jp":true,"ichikawa.chiba.jp":true,"ichinomiya.chiba.jp":true,"inzai.chiba.jp":true,"isumi.chiba.jp":true,"kamagaya.chiba.jp":true,"kamogawa.chiba.jp":true,"kashiwa.chiba.jp":true,"katori.chiba.jp":true,"katsuura.chiba.jp":true,"kimitsu.chiba.jp":true,"kisarazu.chiba.jp":true,"kozaki.chiba.jp":true,"kujukuri.chiba.jp":true,"kyonan.chiba.jp":true,"matsudo.chiba.jp":true,"midori.chiba.jp":true,"mihama.chiba.jp":true,"minamiboso.chiba.jp":true,"mobara.chiba.jp":true,"mutsuzawa.chiba.jp":true,"nagara.chiba.jp":true,"nagareyama.chiba.jp":true,"narashino.chiba.jp":true,"narita.chiba.jp":true,"noda.chiba.jp":true,"oamishirasato.chiba.jp":true,"omigawa.chiba.jp":true,"onjuku.chiba.jp":true,"otaki.chiba.jp":true,"sakae.chiba.jp":true,"sakura.chiba.jp":true,"shimofusa.chiba.jp":true,"shirako.chiba.jp":true,"shiroi.chiba.jp":true,"shisui.chiba.jp":true,"sodegaura.chiba.jp":true,"sosa.chiba.jp":true,"tako.chiba.jp":true,"tateyama.chiba.jp":true,"togane.chiba.jp":true,"tohnosho.chiba.jp":true,"tomisato.chiba.jp":true,"urayasu.chiba.jp":true,"yachimata.chiba.jp":true,"yachiyo.chiba.jp":true,"yokaichiba.chiba.jp":true,"yokoshibahikari.chiba.jp":true,"yotsukaido.chiba.jp":true,"ainan.ehime.jp":true,"honai.ehime.jp":true,"ikata.ehime.jp":true,"imabari.ehime.jp":true,"iyo.ehime.jp":true,"kamijima.ehime.jp":true,"kihoku.ehime.jp":true,"kumakogen.ehime.jp":true,"masaki.ehime.jp":true,"matsuno.ehime.jp":true,"matsuyama.ehime.jp":true,"namikata.ehime.jp":true,"niihama.ehime.jp":true,"ozu.ehime.jp":true,"saijo.ehime.jp":true,"seiyo.ehime.jp":true,"shikokuchuo.ehime.jp":true,"tobe.ehime.jp":true,"toon.ehime.jp":true,"uchiko.ehime.jp":true,"uwajima.ehime.jp":true,"yawatahama.ehime.jp":true,"echizen.fukui.jp":true,"eiheiji.fukui.jp":true,"fukui.fukui.jp":true,"ikeda.fukui.jp":true,"katsuyama.fukui.jp":true,"mihama.fukui.jp":true,"minamiechizen.fukui.jp":true,"obama.fukui.jp":true,"ohi.fukui.jp":true,"ono.fukui.jp":true,"sabae.fukui.jp":true,"sakai.fukui.jp":true,"takahama.fukui.jp":true,"tsuruga.fukui.jp":true,"wakasa.fukui.jp":true,"ashiya.fukuoka.jp":true,"buzen.fukuoka.jp":true,"chikugo.fukuoka.jp":true,"chikuho.fukuoka.jp":true,"chikujo.fukuoka.jp":true,"chikushino.fukuoka.jp":true,"chikuzen.fukuoka.jp":true,"chuo.fukuoka.jp":true,"dazaifu.fukuoka.jp":true,"fukuchi.fukuoka.jp":true,"hakata.fukuoka.jp":true,"higashi.fukuoka.jp":true,"hirokawa.fukuoka.jp":true,"hisayama.fukuoka.jp":true,"iizuka.fukuoka.jp":true,"inatsuki.fukuoka.jp":true,"kaho.fukuoka.jp":true,"kasuga.fukuoka.jp":true,"kasuya.fukuoka.jp":true,"kawara.fukuoka.jp":true,"keisen.fukuoka.jp":true,"koga.fukuoka.jp":true,"kurate.fukuoka.jp":true,"kurogi.fukuoka.jp":true,"kurume.fukuoka.jp":true,"minami.fukuoka.jp":true,"miyako.fukuoka.jp":true,"miyama.fukuoka.jp":true,"miyawaka.fukuoka.jp":true,"mizumaki.fukuoka.jp":true,"munakata.fukuoka.jp":true,"nakagawa.fukuoka.jp":true,"nakama.fukuoka.jp":true,"nishi.fukuoka.jp":true,"nogata.fukuoka.jp":true,"ogori.fukuoka.jp":true,"okagaki.fukuoka.jp":true,"okawa.fukuoka.jp":true,"oki.fukuoka.jp":true,"omuta.fukuoka.jp":true,"onga.fukuoka.jp":true,"onojo.fukuoka.jp":true,"oto.fukuoka.jp":true,"saigawa.fukuoka.jp":true,"sasaguri.fukuoka.jp":true,"shingu.fukuoka.jp":true,"shinyoshitomi.fukuoka.jp":true,"shonai.fukuoka.jp":true,"soeda.fukuoka.jp":true,"sue.fukuoka.jp":true,"tachiarai.fukuoka.jp":true,"tagawa.fukuoka.jp":true,"takata.fukuoka.jp":true,"toho.fukuoka.jp":true,"toyotsu.fukuoka.jp":true,"tsuiki.fukuoka.jp":true,"ukiha.fukuoka.jp":true,"umi.fukuoka.jp":true,"usui.fukuoka.jp":true,"yamada.fukuoka.jp":true,"yame.fukuoka.jp":true,"yanagawa.fukuoka.jp":true,"yukuhashi.fukuoka.jp":true,"aizubange.fukushima.jp":true,"aizumisato.fukushima.jp":true,"aizuwakamatsu.fukushima.jp":true,"asakawa.fukushima.jp":true,"bandai.fukushima.jp":true,"date.fukushima.jp":true,"fukushima.fukushima.jp":true,"furudono.fukushima.jp":true,"futaba.fukushima.jp":true,"hanawa.fukushima.jp":true,"higashi.fukushima.jp":true,"hirata.fukushima.jp":true,"hirono.fukushima.jp":true,"iitate.fukushima.jp":true,"inawashiro.fukushima.jp":true,"ishikawa.fukushima.jp":true,"iwaki.fukushima.jp":true,"izumizaki.fukushima.jp":true,"kagamiishi.fukushima.jp":true,"kaneyama.fukushima.jp":true,"kawamata.fukushima.jp":true,"kitakata.fukushima.jp":true,"kitashiobara.fukushima.jp":true,"koori.fukushima.jp":true,"koriyama.fukushima.jp":true,"kunimi.fukushima.jp":true,"miharu.fukushima.jp":true,"mishima.fukushima.jp":true,"namie.fukushima.jp":true,"nango.fukushima.jp":true,"nishiaizu.fukushima.jp":true,"nishigo.fukushima.jp":true,"okuma.fukushima.jp":true,"omotego.fukushima.jp":true,"ono.fukushima.jp":true,"otama.fukushima.jp":true,"samegawa.fukushima.jp":true,"shimogo.fukushima.jp":true,"shirakawa.fukushima.jp":true,"showa.fukushima.jp":true,"soma.fukushima.jp":true,"sukagawa.fukushima.jp":true,"taishin.fukushima.jp":true,"tamakawa.fukushima.jp":true,"tanagura.fukushima.jp":true,"tenei.fukushima.jp":true,"yabuki.fukushima.jp":true,"yamato.fukushima.jp":true,"yamatsuri.fukushima.jp":true,"yanaizu.fukushima.jp":true,"yugawa.fukushima.jp":true,"anpachi.gifu.jp":true,"ena.gifu.jp":true,"gifu.gifu.jp":true,"ginan.gifu.jp":true,"godo.gifu.jp":true,"gujo.gifu.jp":true,"hashima.gifu.jp":true,"hichiso.gifu.jp":true,"hida.gifu.jp":true,"higashishirakawa.gifu.jp":true,"ibigawa.gifu.jp":true,"ikeda.gifu.jp":true,"kakamigahara.gifu.jp":true,"kani.gifu.jp":true,"kasahara.gifu.jp":true,"kasamatsu.gifu.jp":true,"kawaue.gifu.jp":true,"kitagata.gifu.jp":true,"mino.gifu.jp":true,"minokamo.gifu.jp":true,"mitake.gifu.jp":true,"mizunami.gifu.jp":true,"motosu.gifu.jp":true,"nakatsugawa.gifu.jp":true,"ogaki.gifu.jp":true,"sakahogi.gifu.jp":true,"seki.gifu.jp":true,"sekigahara.gifu.jp":true,"shirakawa.gifu.jp":true,"tajimi.gifu.jp":true,"takayama.gifu.jp":true,"tarui.gifu.jp":true,"toki.gifu.jp":true,"tomika.gifu.jp":true,"wanouchi.gifu.jp":true,"yamagata.gifu.jp":true,"yaotsu.gifu.jp":true,"yoro.gifu.jp":true,"annaka.gunma.jp":true,"chiyoda.gunma.jp":true,"fujioka.gunma.jp":true,"higashiagatsuma.gunma.jp":true,"isesaki.gunma.jp":true,"itakura.gunma.jp":true,"kanna.gunma.jp":true,"kanra.gunma.jp":true,"katashina.gunma.jp":true,"kawaba.gunma.jp":true,"kiryu.gunma.jp":true,"kusatsu.gunma.jp":true,"maebashi.gunma.jp":true,"meiwa.gunma.jp":true,"midori.gunma.jp":true,"minakami.gunma.jp":true,"naganohara.gunma.jp":true,"nakanojo.gunma.jp":true,"nanmoku.gunma.jp":true,"numata.gunma.jp":true,"oizumi.gunma.jp":true,"ora.gunma.jp":true,"ota.gunma.jp":true,"shibukawa.gunma.jp":true,"shimonita.gunma.jp":true,"shinto.gunma.jp":true,"showa.gunma.jp":true,"takasaki.gunma.jp":true,"takayama.gunma.jp":true,"tamamura.gunma.jp":true,"tatebayashi.gunma.jp":true,"tomioka.gunma.jp":true,"tsukiyono.gunma.jp":true,"tsumagoi.gunma.jp":true,"ueno.gunma.jp":true,"yoshioka.gunma.jp":true,"asaminami.hiroshima.jp":true,"daiwa.hiroshima.jp":true,"etajima.hiroshima.jp":true,"fuchu.hiroshima.jp":true,"fukuyama.hiroshima.jp":true,"hatsukaichi.hiroshima.jp":true,"higashihiroshima.hiroshima.jp":true,"hongo.hiroshima.jp":true,"jinsekikogen.hiroshima.jp":true,"kaita.hiroshima.jp":true,"kui.hiroshima.jp":true,"kumano.hiroshima.jp":true,"kure.hiroshima.jp":true,"mihara.hiroshima.jp":true,"miyoshi.hiroshima.jp":true,"naka.hiroshima.jp":true,"onomichi.hiroshima.jp":true,"osakikamijima.hiroshima.jp":true,"otake.hiroshima.jp":true,"saka.hiroshima.jp":true,"sera.hiroshima.jp":true,"seranishi.hiroshima.jp":true,"shinichi.hiroshima.jp":true,"shobara.hiroshima.jp":true,"takehara.hiroshima.jp":true,"abashiri.hokkaido.jp":true,"abira.hokkaido.jp":true,"aibetsu.hokkaido.jp":true,"akabira.hokkaido.jp":true,"akkeshi.hokkaido.jp":true,"asahikawa.hokkaido.jp":true,"ashibetsu.hokkaido.jp":true,"ashoro.hokkaido.jp":true,"assabu.hokkaido.jp":true,"atsuma.hokkaido.jp":true,"bibai.hokkaido.jp":true,"biei.hokkaido.jp":true,"bifuka.hokkaido.jp":true,"bihoro.hokkaido.jp":true,"biratori.hokkaido.jp":true,"chippubetsu.hokkaido.jp":true,"chitose.hokkaido.jp":true,"date.hokkaido.jp":true,"ebetsu.hokkaido.jp":true,"embetsu.hokkaido.jp":true,"eniwa.hokkaido.jp":true,"erimo.hokkaido.jp":true,"esan.hokkaido.jp":true,"esashi.hokkaido.jp":true,"fukagawa.hokkaido.jp":true,"fukushima.hokkaido.jp":true,"furano.hokkaido.jp":true,"furubira.hokkaido.jp":true,"haboro.hokkaido.jp":true,"hakodate.hokkaido.jp":true,"hamatonbetsu.hokkaido.jp":true,"hidaka.hokkaido.jp":true,"higashikagura.hokkaido.jp":true,"higashikawa.hokkaido.jp":true,"hiroo.hokkaido.jp":true,"hokuryu.hokkaido.jp":true,"hokuto.hokkaido.jp":true,"honbetsu.hokkaido.jp":true,"horokanai.hokkaido.jp":true,"horonobe.hokkaido.jp":true,"ikeda.hokkaido.jp":true,"imakane.hokkaido.jp":true,"ishikari.hokkaido.jp":true,"iwamizawa.hokkaido.jp":true,"iwanai.hokkaido.jp":true,"kamifurano.hokkaido.jp":true,"kamikawa.hokkaido.jp":true,"kamishihoro.hokkaido.jp":true,"kamisunagawa.hokkaido.jp":true,"kamoenai.hokkaido.jp":true,"kayabe.hokkaido.jp":true,"kembuchi.hokkaido.jp":true,"kikonai.hokkaido.jp":true,"kimobetsu.hokkaido.jp":true,"kitahiroshima.hokkaido.jp":true,"kitami.hokkaido.jp":true,"kiyosato.hokkaido.jp":true,"koshimizu.hokkaido.jp":true,"kunneppu.hokkaido.jp":true,"kuriyama.hokkaido.jp":true,"kuromatsunai.hokkaido.jp":true,"kushiro.hokkaido.jp":true,"kutchan.hokkaido.jp":true,"kyowa.hokkaido.jp":true,"mashike.hokkaido.jp":true,"matsumae.hokkaido.jp":true,"mikasa.hokkaido.jp":true,"minamifurano.hokkaido.jp":true,"mombetsu.hokkaido.jp":true,"moseushi.hokkaido.jp":true,"mukawa.hokkaido.jp":true,"muroran.hokkaido.jp":true,"naie.hokkaido.jp":true,"nakagawa.hokkaido.jp":true,"nakasatsunai.hokkaido.jp":true,"nakatombetsu.hokkaido.jp":true,"nanae.hokkaido.jp":true,"nanporo.hokkaido.jp":true,"nayoro.hokkaido.jp":true,"nemuro.hokkaido.jp":true,"niikappu.hokkaido.jp":true,"niki.hokkaido.jp":true,"nishiokoppe.hokkaido.jp":true,"noboribetsu.hokkaido.jp":true,"numata.hokkaido.jp":true,"obihiro.hokkaido.jp":true,"obira.hokkaido.jp":true,"oketo.hokkaido.jp":true,"okoppe.hokkaido.jp":true,"otaru.hokkaido.jp":true,"otobe.hokkaido.jp":true,"otofuke.hokkaido.jp":true,"otoineppu.hokkaido.jp":true,"oumu.hokkaido.jp":true,"ozora.hokkaido.jp":true,"pippu.hokkaido.jp":true,"rankoshi.hokkaido.jp":true,"rebun.hokkaido.jp":true,"rikubetsu.hokkaido.jp":true,"rishiri.hokkaido.jp":true,"rishirifuji.hokkaido.jp":true,"saroma.hokkaido.jp":true,"sarufutsu.hokkaido.jp":true,"shakotan.hokkaido.jp":true,"shari.hokkaido.jp":true,"shibecha.hokkaido.jp":true,"shibetsu.hokkaido.jp":true,"shikabe.hokkaido.jp":true,"shikaoi.hokkaido.jp":true,"shimamaki.hokkaido.jp":true,"shimizu.hokkaido.jp":true,"shimokawa.hokkaido.jp":true,"shinshinotsu.hokkaido.jp":true,"shintoku.hokkaido.jp":true,"shiranuka.hokkaido.jp":true,"shiraoi.hokkaido.jp":true,"shiriuchi.hokkaido.jp":true,"sobetsu.hokkaido.jp":true,"sunagawa.hokkaido.jp":true,"taiki.hokkaido.jp":true,"takasu.hokkaido.jp":true,"takikawa.hokkaido.jp":true,"takinoue.hokkaido.jp":true,"teshikaga.hokkaido.jp":true,"tobetsu.hokkaido.jp":true,"tohma.hokkaido.jp":true,"tomakomai.hokkaido.jp":true,"tomari.hokkaido.jp":true,"toya.hokkaido.jp":true,"toyako.hokkaido.jp":true,"toyotomi.hokkaido.jp":true,"toyoura.hokkaido.jp":true,"tsubetsu.hokkaido.jp":true,"tsukigata.hokkaido.jp":true,"urakawa.hokkaido.jp":true,"urausu.hokkaido.jp":true,"uryu.hokkaido.jp":true,"utashinai.hokkaido.jp":true,"wakkanai.hokkaido.jp":true,"wassamu.hokkaido.jp":true,"yakumo.hokkaido.jp":true,"yoichi.hokkaido.jp":true,"aioi.hyogo.jp":true,"akashi.hyogo.jp":true,"ako.hyogo.jp":true,"amagasaki.hyogo.jp":true,"aogaki.hyogo.jp":true,"asago.hyogo.jp":true,"ashiya.hyogo.jp":true,"awaji.hyogo.jp":true,"fukusaki.hyogo.jp":true,"goshiki.hyogo.jp":true,"harima.hyogo.jp":true,"himeji.hyogo.jp":true,"ichikawa.hyogo.jp":true,"inagawa.hyogo.jp":true,"itami.hyogo.jp":true,"kakogawa.hyogo.jp":true,"kamigori.hyogo.jp":true,"kamikawa.hyogo.jp":true,"kasai.hyogo.jp":true,"kasuga.hyogo.jp":true,"kawanishi.hyogo.jp":true,"miki.hyogo.jp":true,"minamiawaji.hyogo.jp":true,"nishinomiya.hyogo.jp":true,"nishiwaki.hyogo.jp":true,"ono.hyogo.jp":true,"sanda.hyogo.jp":true,"sannan.hyogo.jp":true,"sasayama.hyogo.jp":true,"sayo.hyogo.jp":true,"shingu.hyogo.jp":true,"shinonsen.hyogo.jp":true,"shiso.hyogo.jp":true,"sumoto.hyogo.jp":true,"taishi.hyogo.jp":true,"taka.hyogo.jp":true,"takarazuka.hyogo.jp":true,"takasago.hyogo.jp":true,"takino.hyogo.jp":true,"tamba.hyogo.jp":true,"tatsuno.hyogo.jp":true,"toyooka.hyogo.jp":true,"yabu.hyogo.jp":true,"yashiro.hyogo.jp":true,"yoka.hyogo.jp":true,"yokawa.hyogo.jp":true,"ami.ibaraki.jp":true,"asahi.ibaraki.jp":true,"bando.ibaraki.jp":true,"chikusei.ibaraki.jp":true,"daigo.ibaraki.jp":true,"fujishiro.ibaraki.jp":true,"hitachi.ibaraki.jp":true,"hitachinaka.ibaraki.jp":true,"hitachiomiya.ibaraki.jp":true,"hitachiota.ibaraki.jp":true,"ibaraki.ibaraki.jp":true,"ina.ibaraki.jp":true,"inashiki.ibaraki.jp":true,"itako.ibaraki.jp":true,"iwama.ibaraki.jp":true,"joso.ibaraki.jp":true,"kamisu.ibaraki.jp":true,"kasama.ibaraki.jp":true,"kashima.ibaraki.jp":true,"kasumigaura.ibaraki.jp":true,"koga.ibaraki.jp":true,"miho.ibaraki.jp":true,"mito.ibaraki.jp":true,"moriya.ibaraki.jp":true,"naka.ibaraki.jp":true,"namegata.ibaraki.jp":true,"oarai.ibaraki.jp":true,"ogawa.ibaraki.jp":true,"omitama.ibaraki.jp":true,"ryugasaki.ibaraki.jp":true,"sakai.ibaraki.jp":true,"sakuragawa.ibaraki.jp":true,"shimodate.ibaraki.jp":true,"shimotsuma.ibaraki.jp":true,"shirosato.ibaraki.jp":true,"sowa.ibaraki.jp":true,"suifu.ibaraki.jp":true,"takahagi.ibaraki.jp":true,"tamatsukuri.ibaraki.jp":true,"tokai.ibaraki.jp":true,"tomobe.ibaraki.jp":true,"tone.ibaraki.jp":true,"toride.ibaraki.jp":true,"tsuchiura.ibaraki.jp":true,"tsukuba.ibaraki.jp":true,"uchihara.ibaraki.jp":true,"ushiku.ibaraki.jp":true,"yachiyo.ibaraki.jp":true,"yamagata.ibaraki.jp":true,"yawara.ibaraki.jp":true,"yuki.ibaraki.jp":true,"anamizu.ishikawa.jp":true,"hakui.ishikawa.jp":true,"hakusan.ishikawa.jp":true,"kaga.ishikawa.jp":true,"kahoku.ishikawa.jp":true,"kanazawa.ishikawa.jp":true,"kawakita.ishikawa.jp":true,"komatsu.ishikawa.jp":true,"nakanoto.ishikawa.jp":true,"nanao.ishikawa.jp":true,"nomi.ishikawa.jp":true,"nonoichi.ishikawa.jp":true,"noto.ishikawa.jp":true,"shika.ishikawa.jp":true,"suzu.ishikawa.jp":true,"tsubata.ishikawa.jp":true,"tsurugi.ishikawa.jp":true,"uchinada.ishikawa.jp":true,"wajima.ishikawa.jp":true,"fudai.iwate.jp":true,"fujisawa.iwate.jp":true,"hanamaki.iwate.jp":true,"hiraizumi.iwate.jp":true,"hirono.iwate.jp":true,"ichinohe.iwate.jp":true,"ichinoseki.iwate.jp":true,"iwaizumi.iwate.jp":true,"iwate.iwate.jp":true,"joboji.iwate.jp":true,"kamaishi.iwate.jp":true,"kanegasaki.iwate.jp":true,"karumai.iwate.jp":true,"kawai.iwate.jp":true,"kitakami.iwate.jp":true,"kuji.iwate.jp":true,"kunohe.iwate.jp":true,"kuzumaki.iwate.jp":true,"miyako.iwate.jp":true,"mizusawa.iwate.jp":true,"morioka.iwate.jp":true,"ninohe.iwate.jp":true,"noda.iwate.jp":true,"ofunato.iwate.jp":true,"oshu.iwate.jp":true,"otsuchi.iwate.jp":true,"rikuzentakata.iwate.jp":true,"shiwa.iwate.jp":true,"shizukuishi.iwate.jp":true,"sumita.iwate.jp":true,"tanohata.iwate.jp":true,"tono.iwate.jp":true,"yahaba.iwate.jp":true,"yamada.iwate.jp":true,"ayagawa.kagawa.jp":true,"higashikagawa.kagawa.jp":true,"kanonji.kagawa.jp":true,"kotohira.kagawa.jp":true,"manno.kagawa.jp":true,"marugame.kagawa.jp":true,"mitoyo.kagawa.jp":true,"naoshima.kagawa.jp":true,"sanuki.kagawa.jp":true,"tadotsu.kagawa.jp":true,"takamatsu.kagawa.jp":true,"tonosho.kagawa.jp":true,"uchinomi.kagawa.jp":true,"utazu.kagawa.jp":true,"zentsuji.kagawa.jp":true,"akune.kagoshima.jp":true,"amami.kagoshima.jp":true,"hioki.kagoshima.jp":true,"isa.kagoshima.jp":true,"isen.kagoshima.jp":true,"izumi.kagoshima.jp":true,"kagoshima.kagoshima.jp":true,"kanoya.kagoshima.jp":true,"kawanabe.kagoshima.jp":true,"kinko.kagoshima.jp":true,"kouyama.kagoshima.jp":true,"makurazaki.kagoshima.jp":true,"matsumoto.kagoshima.jp":true,"minamitane.kagoshima.jp":true,"nakatane.kagoshima.jp":true,"nishinoomote.kagoshima.jp":true,"satsumasendai.kagoshima.jp":true,"soo.kagoshima.jp":true,"tarumizu.kagoshima.jp":true,"yusui.kagoshima.jp":true,"aikawa.kanagawa.jp":true,"atsugi.kanagawa.jp":true,"ayase.kanagawa.jp":true,"chigasaki.kanagawa.jp":true,"ebina.kanagawa.jp":true,"fujisawa.kanagawa.jp":true,"hadano.kanagawa.jp":true,"hakone.kanagawa.jp":true,"hiratsuka.kanagawa.jp":true,"isehara.kanagawa.jp":true,"kaisei.kanagawa.jp":true,"kamakura.kanagawa.jp":true,"kiyokawa.kanagawa.jp":true,"matsuda.kanagawa.jp":true,"minamiashigara.kanagawa.jp":true,"miura.kanagawa.jp":true,"nakai.kanagawa.jp":true,"ninomiya.kanagawa.jp":true,"odawara.kanagawa.jp":true,"oi.kanagawa.jp":true,"oiso.kanagawa.jp":true,"sagamihara.kanagawa.jp":true,"samukawa.kanagawa.jp":true,"tsukui.kanagawa.jp":true,"yamakita.kanagawa.jp":true,"yamato.kanagawa.jp":true,"yokosuka.kanagawa.jp":true,"yugawara.kanagawa.jp":true,"zama.kanagawa.jp":true,"zushi.kanagawa.jp":true,"aki.kochi.jp":true,"geisei.kochi.jp":true,"hidaka.kochi.jp":true,"higashitsuno.kochi.jp":true,"ino.kochi.jp":true,"kagami.kochi.jp":true,"kami.kochi.jp":true,"kitagawa.kochi.jp":true,"kochi.kochi.jp":true,"mihara.kochi.jp":true,"motoyama.kochi.jp":true,"muroto.kochi.jp":true,"nahari.kochi.jp":true,"nakamura.kochi.jp":true,"nankoku.kochi.jp":true,"nishitosa.kochi.jp":true,"niyodogawa.kochi.jp":true,"ochi.kochi.jp":true,"okawa.kochi.jp":true,"otoyo.kochi.jp":true,"otsuki.kochi.jp":true,"sakawa.kochi.jp":true,"sukumo.kochi.jp":true,"susaki.kochi.jp":true,"tosa.kochi.jp":true,"tosashimizu.kochi.jp":true,"toyo.kochi.jp":true,"tsuno.kochi.jp":true,"umaji.kochi.jp":true,"yasuda.kochi.jp":true,"yusuhara.kochi.jp":true,"amakusa.kumamoto.jp":true,"arao.kumamoto.jp":true,"aso.kumamoto.jp":true,"choyo.kumamoto.jp":true,"gyokuto.kumamoto.jp":true,"hitoyoshi.kumamoto.jp":true,"kamiamakusa.kumamoto.jp":true,"kashima.kumamoto.jp":true,"kikuchi.kumamoto.jp":true,"kosa.kumamoto.jp":true,"kumamoto.kumamoto.jp":true,"mashiki.kumamoto.jp":true,"mifune.kumamoto.jp":true,"minamata.kumamoto.jp":true,"minamioguni.kumamoto.jp":true,"nagasu.kumamoto.jp":true,"nishihara.kumamoto.jp":true,"oguni.kumamoto.jp":true,"ozu.kumamoto.jp":true,"sumoto.kumamoto.jp":true,"takamori.kumamoto.jp":true,"uki.kumamoto.jp":true,"uto.kumamoto.jp":true,"yamaga.kumamoto.jp":true,"yamato.kumamoto.jp":true,"yatsushiro.kumamoto.jp":true,"ayabe.kyoto.jp":true,"fukuchiyama.kyoto.jp":true,"higashiyama.kyoto.jp":true,"ide.kyoto.jp":true,"ine.kyoto.jp":true,"joyo.kyoto.jp":true,"kameoka.kyoto.jp":true,"kamo.kyoto.jp":true,"kita.kyoto.jp":true,"kizu.kyoto.jp":true,"kumiyama.kyoto.jp":true,"kyotamba.kyoto.jp":true,"kyotanabe.kyoto.jp":true,"kyotango.kyoto.jp":true,"maizuru.kyoto.jp":true,"minami.kyoto.jp":true,"minamiyamashiro.kyoto.jp":true,"miyazu.kyoto.jp":true,"muko.kyoto.jp":true,"nagaokakyo.kyoto.jp":true,"nakagyo.kyoto.jp":true,"nantan.kyoto.jp":true,"oyamazaki.kyoto.jp":true,"sakyo.kyoto.jp":true,"seika.kyoto.jp":true,"tanabe.kyoto.jp":true,"uji.kyoto.jp":true,"ujitawara.kyoto.jp":true,"wazuka.kyoto.jp":true,"yamashina.kyoto.jp":true,"yawata.kyoto.jp":true,"asahi.mie.jp":true,"inabe.mie.jp":true,"ise.mie.jp":true,"kameyama.mie.jp":true,"kawagoe.mie.jp":true,"kiho.mie.jp":true,"kisosaki.mie.jp":true,"kiwa.mie.jp":true,"komono.mie.jp":true,"kumano.mie.jp":true,"kuwana.mie.jp":true,"matsusaka.mie.jp":true,"meiwa.mie.jp":true,"mihama.mie.jp":true,"minamiise.mie.jp":true,"misugi.mie.jp":true,"miyama.mie.jp":true,"nabari.mie.jp":true,"shima.mie.jp":true,"suzuka.mie.jp":true,"tado.mie.jp":true,"taiki.mie.jp":true,"taki.mie.jp":true,"tamaki.mie.jp":true,"toba.mie.jp":true,"tsu.mie.jp":true,"udono.mie.jp":true,"ureshino.mie.jp":true,"watarai.mie.jp":true,"yokkaichi.mie.jp":true,"furukawa.miyagi.jp":true,"higashimatsushima.miyagi.jp":true,"ishinomaki.miyagi.jp":true,"iwanuma.miyagi.jp":true,"kakuda.miyagi.jp":true,"kami.miyagi.jp":true,"kawasaki.miyagi.jp":true,"kesennuma.miyagi.jp":true,"marumori.miyagi.jp":true,"matsushima.miyagi.jp":true,"minamisanriku.miyagi.jp":true,"misato.miyagi.jp":true,"murata.miyagi.jp":true,"natori.miyagi.jp":true,"ogawara.miyagi.jp":true,"ohira.miyagi.jp":true,"onagawa.miyagi.jp":true,"osaki.miyagi.jp":true,"rifu.miyagi.jp":true,"semine.miyagi.jp":true,"shibata.miyagi.jp":true,"shichikashuku.miyagi.jp":true,"shikama.miyagi.jp":true,"shiogama.miyagi.jp":true,"shiroishi.miyagi.jp":true,"tagajo.miyagi.jp":true,"taiwa.miyagi.jp":true,"tome.miyagi.jp":true,"tomiya.miyagi.jp":true,"wakuya.miyagi.jp":true,"watari.miyagi.jp":true,"yamamoto.miyagi.jp":true,"zao.miyagi.jp":true,"aya.miyazaki.jp":true,"ebino.miyazaki.jp":true,"gokase.miyazaki.jp":true,"hyuga.miyazaki.jp":true,"kadogawa.miyazaki.jp":true,"kawaminami.miyazaki.jp":true,"kijo.miyazaki.jp":true,"kitagawa.miyazaki.jp":true,"kitakata.miyazaki.jp":true,"kitaura.miyazaki.jp":true,"kobayashi.miyazaki.jp":true,"kunitomi.miyazaki.jp":true,"kushima.miyazaki.jp":true,"mimata.miyazaki.jp":true,"miyakonojo.miyazaki.jp":true,"miyazaki.miyazaki.jp":true,"morotsuka.miyazaki.jp":true,"nichinan.miyazaki.jp":true,"nishimera.miyazaki.jp":true,"nobeoka.miyazaki.jp":true,"saito.miyazaki.jp":true,"shiiba.miyazaki.jp":true,"shintomi.miyazaki.jp":true,"takaharu.miyazaki.jp":true,"takanabe.miyazaki.jp":true,"takazaki.miyazaki.jp":true,"tsuno.miyazaki.jp":true,"achi.nagano.jp":true,"agematsu.nagano.jp":true,"anan.nagano.jp":true,"aoki.nagano.jp":true,"asahi.nagano.jp":true,"azumino.nagano.jp":true,"chikuhoku.nagano.jp":true,"chikuma.nagano.jp":true,"chino.nagano.jp":true,"fujimi.nagano.jp":true,"hakuba.nagano.jp":true,"hara.nagano.jp":true,"hiraya.nagano.jp":true,"iida.nagano.jp":true,"iijima.nagano.jp":true,"iiyama.nagano.jp":true,"iizuna.nagano.jp":true,"ikeda.nagano.jp":true,"ikusaka.nagano.jp":true,"ina.nagano.jp":true,"karuizawa.nagano.jp":true,"kawakami.nagano.jp":true,"kiso.nagano.jp":true,"kisofukushima.nagano.jp":true,"kitaaiki.nagano.jp":true,"komagane.nagano.jp":true,"komoro.nagano.jp":true,"matsukawa.nagano.jp":true,"matsumoto.nagano.jp":true,"miasa.nagano.jp":true,"minamiaiki.nagano.jp":true,"minamimaki.nagano.jp":true,"minamiminowa.nagano.jp":true,"minowa.nagano.jp":true,"miyada.nagano.jp":true,"miyota.nagano.jp":true,"mochizuki.nagano.jp":true,"nagano.nagano.jp":true,"nagawa.nagano.jp":true,"nagiso.nagano.jp":true,"nakagawa.nagano.jp":true,"nakano.nagano.jp":true,"nozawaonsen.nagano.jp":true,"obuse.nagano.jp":true,"ogawa.nagano.jp":true,"okaya.nagano.jp":true,"omachi.nagano.jp":true,"omi.nagano.jp":true,"ookuwa.nagano.jp":true,"ooshika.nagano.jp":true,"otaki.nagano.jp":true,"otari.nagano.jp":true,"sakae.nagano.jp":true,"sakaki.nagano.jp":true,"saku.nagano.jp":true,"sakuho.nagano.jp":true,"shimosuwa.nagano.jp":true,"shinanomachi.nagano.jp":true,"shiojiri.nagano.jp":true,"suwa.nagano.jp":true,"suzaka.nagano.jp":true,"takagi.nagano.jp":true,"takamori.nagano.jp":true,"takayama.nagano.jp":true,"tateshina.nagano.jp":true,"tatsuno.nagano.jp":true,"togakushi.nagano.jp":true,"togura.nagano.jp":true,"tomi.nagano.jp":true,"ueda.nagano.jp":true,"wada.nagano.jp":true,"yamagata.nagano.jp":true,"yamanouchi.nagano.jp":true,"yasaka.nagano.jp":true,"yasuoka.nagano.jp":true,"chijiwa.nagasaki.jp":true,"futsu.nagasaki.jp":true,"goto.nagasaki.jp":true,"hasami.nagasaki.jp":true,"hirado.nagasaki.jp":true,"iki.nagasaki.jp":true,"isahaya.nagasaki.jp":true,"kawatana.nagasaki.jp":true,"kuchinotsu.nagasaki.jp":true,"matsuura.nagasaki.jp":true,"nagasaki.nagasaki.jp":true,"obama.nagasaki.jp":true,"omura.nagasaki.jp":true,"oseto.nagasaki.jp":true,"saikai.nagasaki.jp":true,"sasebo.nagasaki.jp":true,"seihi.nagasaki.jp":true,"shimabara.nagasaki.jp":true,"shinkamigoto.nagasaki.jp":true,"togitsu.nagasaki.jp":true,"tsushima.nagasaki.jp":true,"unzen.nagasaki.jp":true,"ando.nara.jp":true,"gose.nara.jp":true,"heguri.nara.jp":true,"higashiyoshino.nara.jp":true,"ikaruga.nara.jp":true,"ikoma.nara.jp":true,"kamikitayama.nara.jp":true,"kanmaki.nara.jp":true,"kashiba.nara.jp":true,"kashihara.nara.jp":true,"katsuragi.nara.jp":true,"kawai.nara.jp":true,"kawakami.nara.jp":true,"kawanishi.nara.jp":true,"koryo.nara.jp":true,"kurotaki.nara.jp":true,"mitsue.nara.jp":true,"miyake.nara.jp":true,"nara.nara.jp":true,"nosegawa.nara.jp":true,"oji.nara.jp":true,"ouda.nara.jp":true,"oyodo.nara.jp":true,"sakurai.nara.jp":true,"sango.nara.jp":true,"shimoichi.nara.jp":true,"shimokitayama.nara.jp":true,"shinjo.nara.jp":true,"soni.nara.jp":true,"takatori.nara.jp":true,"tawaramoto.nara.jp":true,"tenkawa.nara.jp":true,"tenri.nara.jp":true,"uda.nara.jp":true,"yamatokoriyama.nara.jp":true,"yamatotakada.nara.jp":true,"yamazoe.nara.jp":true,"yoshino.nara.jp":true,"aga.niigata.jp":true,"agano.niigata.jp":true,"gosen.niigata.jp":true,"itoigawa.niigata.jp":true,"izumozaki.niigata.jp":true,"joetsu.niigata.jp":true,"kamo.niigata.jp":true,"kariwa.niigata.jp":true,"kashiwazaki.niigata.jp":true,"minamiuonuma.niigata.jp":true,"mitsuke.niigata.jp":true,"muika.niigata.jp":true,"murakami.niigata.jp":true,"myoko.niigata.jp":true,"nagaoka.niigata.jp":true,"niigata.niigata.jp":true,"ojiya.niigata.jp":true,"omi.niigata.jp":true,"sado.niigata.jp":true,"sanjo.niigata.jp":true,"seiro.niigata.jp":true,"seirou.niigata.jp":true,"sekikawa.niigata.jp":true,"shibata.niigata.jp":true,"tagami.niigata.jp":true,"tainai.niigata.jp":true,"tochio.niigata.jp":true,"tokamachi.niigata.jp":true,"tsubame.niigata.jp":true,"tsunan.niigata.jp":true,"uonuma.niigata.jp":true,"yahiko.niigata.jp":true,"yoita.niigata.jp":true,"yuzawa.niigata.jp":true,"beppu.oita.jp":true,"bungoono.oita.jp":true,"bungotakada.oita.jp":true,"hasama.oita.jp":true,"hiji.oita.jp":true,"himeshima.oita.jp":true,"hita.oita.jp":true,"kamitsue.oita.jp":true,"kokonoe.oita.jp":true,"kuju.oita.jp":true,"kunisaki.oita.jp":true,"kusu.oita.jp":true,"oita.oita.jp":true,"saiki.oita.jp":true,"taketa.oita.jp":true,"tsukumi.oita.jp":true,"usa.oita.jp":true,"usuki.oita.jp":true,"yufu.oita.jp":true,"akaiwa.okayama.jp":true,"asakuchi.okayama.jp":true,"bizen.okayama.jp":true,"hayashima.okayama.jp":true,"ibara.okayama.jp":true,"kagamino.okayama.jp":true,"kasaoka.okayama.jp":true,"kibichuo.okayama.jp":true,"kumenan.okayama.jp":true,"kurashiki.okayama.jp":true,"maniwa.okayama.jp":true,"misaki.okayama.jp":true,"nagi.okayama.jp":true,"niimi.okayama.jp":true,"nishiawakura.okayama.jp":true,"okayama.okayama.jp":true,"satosho.okayama.jp":true,"setouchi.okayama.jp":true,"shinjo.okayama.jp":true,"shoo.okayama.jp":true,"soja.okayama.jp":true,"takahashi.okayama.jp":true,"tamano.okayama.jp":true,"tsuyama.okayama.jp":true,"wake.okayama.jp":true,"yakage.okayama.jp":true,"aguni.okinawa.jp":true,"ginowan.okinawa.jp":true,"ginoza.okinawa.jp":true,"gushikami.okinawa.jp":true,"haebaru.okinawa.jp":true,"higashi.okinawa.jp":true,"hirara.okinawa.jp":true,"iheya.okinawa.jp":true,"ishigaki.okinawa.jp":true,"ishikawa.okinawa.jp":true,"itoman.okinawa.jp":true,"izena.okinawa.jp":true,"kadena.okinawa.jp":true,"kin.okinawa.jp":true,"kitadaito.okinawa.jp":true,"kitanakagusuku.okinawa.jp":true,"kumejima.okinawa.jp":true,"kunigami.okinawa.jp":true,"minamidaito.okinawa.jp":true,"motobu.okinawa.jp":true,"nago.okinawa.jp":true,"naha.okinawa.jp":true,"nakagusuku.okinawa.jp":true,"nakijin.okinawa.jp":true,"nanjo.okinawa.jp":true,"nishihara.okinawa.jp":true,"ogimi.okinawa.jp":true,"okinawa.okinawa.jp":true,"onna.okinawa.jp":true,"shimoji.okinawa.jp":true,"taketomi.okinawa.jp":true,"tarama.okinawa.jp":true,"tokashiki.okinawa.jp":true,"tomigusuku.okinawa.jp":true,"tonaki.okinawa.jp":true,"urasoe.okinawa.jp":true,"uruma.okinawa.jp":true,"yaese.okinawa.jp":true,"yomitan.okinawa.jp":true,"yonabaru.okinawa.jp":true,"yonaguni.okinawa.jp":true,"zamami.okinawa.jp":true,"abeno.osaka.jp":true,"chihayaakasaka.osaka.jp":true,"chuo.osaka.jp":true,"daito.osaka.jp":true,"fujiidera.osaka.jp":true,"habikino.osaka.jp":true,"hannan.osaka.jp":true,"higashiosaka.osaka.jp":true,"higashisumiyoshi.osaka.jp":true,"higashiyodogawa.osaka.jp":true,"hirakata.osaka.jp":true,"ibaraki.osaka.jp":true,"ikeda.osaka.jp":true,"izumi.osaka.jp":true,"izumiotsu.osaka.jp":true,"izumisano.osaka.jp":true,"kadoma.osaka.jp":true,"kaizuka.osaka.jp":true,"kanan.osaka.jp":true,"kashiwara.osaka.jp":true,"katano.osaka.jp":true,"kawachinagano.osaka.jp":true,"kishiwada.osaka.jp":true,"kita.osaka.jp":true,"kumatori.osaka.jp":true,"matsubara.osaka.jp":true,"minato.osaka.jp":true,"minoh.osaka.jp":true,"misaki.osaka.jp":true,"moriguchi.osaka.jp":true,"neyagawa.osaka.jp":true,"nishi.osaka.jp":true,"nose.osaka.jp":true,"osakasayama.osaka.jp":true,"sakai.osaka.jp":true,"sayama.osaka.jp":true,"sennan.osaka.jp":true,"settsu.osaka.jp":true,"shijonawate.osaka.jp":true,"shimamoto.osaka.jp":true,"suita.osaka.jp":true,"tadaoka.osaka.jp":true,"taishi.osaka.jp":true,"tajiri.osaka.jp":true,"takaishi.osaka.jp":true,"takatsuki.osaka.jp":true,"tondabayashi.osaka.jp":true,"toyonaka.osaka.jp":true,"toyono.osaka.jp":true,"yao.osaka.jp":true,"ariake.saga.jp":true,"arita.saga.jp":true,"fukudomi.saga.jp":true,"genkai.saga.jp":true,"hamatama.saga.jp":true,"hizen.saga.jp":true,"imari.saga.jp":true,"kamimine.saga.jp":true,"kanzaki.saga.jp":true,"karatsu.saga.jp":true,"kashima.saga.jp":true,"kitagata.saga.jp":true,"kitahata.saga.jp":true,"kiyama.saga.jp":true,"kouhoku.saga.jp":true,"kyuragi.saga.jp":true,"nishiarita.saga.jp":true,"ogi.saga.jp":true,"omachi.saga.jp":true,"ouchi.saga.jp":true,"saga.saga.jp":true,"shiroishi.saga.jp":true,"taku.saga.jp":true,"tara.saga.jp":true,"tosu.saga.jp":true,"yoshinogari.saga.jp":true,"arakawa.saitama.jp":true,"asaka.saitama.jp":true,"chichibu.saitama.jp":true,"fujimi.saitama.jp":true,"fujimino.saitama.jp":true,"fukaya.saitama.jp":true,"hanno.saitama.jp":true,"hanyu.saitama.jp":true,"hasuda.saitama.jp":true,"hatogaya.saitama.jp":true,"hatoyama.saitama.jp":true,"hidaka.saitama.jp":true,"higashichichibu.saitama.jp":true,"higashimatsuyama.saitama.jp":true,"honjo.saitama.jp":true,"ina.saitama.jp":true,"iruma.saitama.jp":true,"iwatsuki.saitama.jp":true,"kamiizumi.saitama.jp":true,"kamikawa.saitama.jp":true,"kamisato.saitama.jp":true,"kasukabe.saitama.jp":true,"kawagoe.saitama.jp":true,"kawaguchi.saitama.jp":true,"kawajima.saitama.jp":true,"kazo.saitama.jp":true,"kitamoto.saitama.jp":true,"koshigaya.saitama.jp":true,"kounosu.saitama.jp":true,"kuki.saitama.jp":true,"kumagaya.saitama.jp":true,"matsubushi.saitama.jp":true,"minano.saitama.jp":true,"misato.saitama.jp":true,"miyashiro.saitama.jp":true,"miyoshi.saitama.jp":true,"moroyama.saitama.jp":true,"nagatoro.saitama.jp":true,"namegawa.saitama.jp":true,"niiza.saitama.jp":true,"ogano.saitama.jp":true,"ogawa.saitama.jp":true,"ogose.saitama.jp":true,"okegawa.saitama.jp":true,"omiya.saitama.jp":true,"otaki.saitama.jp":true,"ranzan.saitama.jp":true,"ryokami.saitama.jp":true,"saitama.saitama.jp":true,"sakado.saitama.jp":true,"satte.saitama.jp":true,"sayama.saitama.jp":true,"shiki.saitama.jp":true,"shiraoka.saitama.jp":true,"soka.saitama.jp":true,"sugito.saitama.jp":true,"toda.saitama.jp":true,"tokigawa.saitama.jp":true,"tokorozawa.saitama.jp":true,"tsurugashima.saitama.jp":true,"urawa.saitama.jp":true,"warabi.saitama.jp":true,"yashio.saitama.jp":true,"yokoze.saitama.jp":true,"yono.saitama.jp":true,"yorii.saitama.jp":true,"yoshida.saitama.jp":true,"yoshikawa.saitama.jp":true,"yoshimi.saitama.jp":true,"aisho.shiga.jp":true,"gamo.shiga.jp":true,"higashiomi.shiga.jp":true,"hikone.shiga.jp":true,"koka.shiga.jp":true,"konan.shiga.jp":true,"kosei.shiga.jp":true,"koto.shiga.jp":true,"kusatsu.shiga.jp":true,"maibara.shiga.jp":true,"moriyama.shiga.jp":true,"nagahama.shiga.jp":true,"nishiazai.shiga.jp":true,"notogawa.shiga.jp":true,"omihachiman.shiga.jp":true,"otsu.shiga.jp":true,"ritto.shiga.jp":true,"ryuoh.shiga.jp":true,"takashima.shiga.jp":true,"takatsuki.shiga.jp":true,"torahime.shiga.jp":true,"toyosato.shiga.jp":true,"yasu.shiga.jp":true,"akagi.shimane.jp":true,"ama.shimane.jp":true,"gotsu.shimane.jp":true,"hamada.shimane.jp":true,"higashiizumo.shimane.jp":true,"hikawa.shimane.jp":true,"hikimi.shimane.jp":true,"izumo.shimane.jp":true,"kakinoki.shimane.jp":true,"masuda.shimane.jp":true,"matsue.shimane.jp":true,"misato.shimane.jp":true,"nishinoshima.shimane.jp":true,"ohda.shimane.jp":true,"okinoshima.shimane.jp":true,"okuizumo.shimane.jp":true,"shimane.shimane.jp":true,"tamayu.shimane.jp":true,"tsuwano.shimane.jp":true,"unnan.shimane.jp":true,"yakumo.shimane.jp":true,"yasugi.shimane.jp":true,"yatsuka.shimane.jp":true,"arai.shizuoka.jp":true,"atami.shizuoka.jp":true,"fuji.shizuoka.jp":true,"fujieda.shizuoka.jp":true,"fujikawa.shizuoka.jp":true,"fujinomiya.shizuoka.jp":true,"fukuroi.shizuoka.jp":true,"gotemba.shizuoka.jp":true,"haibara.shizuoka.jp":true,"hamamatsu.shizuoka.jp":true,"higashiizu.shizuoka.jp":true,"ito.shizuoka.jp":true,"iwata.shizuoka.jp":true,"izu.shizuoka.jp":true,"izunokuni.shizuoka.jp":true,"kakegawa.shizuoka.jp":true,"kannami.shizuoka.jp":true,"kawanehon.shizuoka.jp":true,"kawazu.shizuoka.jp":true,"kikugawa.shizuoka.jp":true,"kosai.shizuoka.jp":true,"makinohara.shizuoka.jp":true,"matsuzaki.shizuoka.jp":true,"minamiizu.shizuoka.jp":true,"mishima.shizuoka.jp":true,"morimachi.shizuoka.jp":true,"nishiizu.shizuoka.jp":true,"numazu.shizuoka.jp":true,"omaezaki.shizuoka.jp":true,"shimada.shizuoka.jp":true,"shimizu.shizuoka.jp":true,"shimoda.shizuoka.jp":true,"shizuoka.shizuoka.jp":true,"susono.shizuoka.jp":true,"yaizu.shizuoka.jp":true,"yoshida.shizuoka.jp":true,"ashikaga.tochigi.jp":true,"bato.tochigi.jp":true,"haga.tochigi.jp":true,"ichikai.tochigi.jp":true,"iwafune.tochigi.jp":true,"kaminokawa.tochigi.jp":true,"kanuma.tochigi.jp":true,"karasuyama.tochigi.jp":true,"kuroiso.tochigi.jp":true,"mashiko.tochigi.jp":true,"mibu.tochigi.jp":true,"moka.tochigi.jp":true,"motegi.tochigi.jp":true,"nasu.tochigi.jp":true,"nasushiobara.tochigi.jp":true,"nikko.tochigi.jp":true,"nishikata.tochigi.jp":true,"nogi.tochigi.jp":true,"ohira.tochigi.jp":true,"ohtawara.tochigi.jp":true,"oyama.tochigi.jp":true,"sakura.tochigi.jp":true,"sano.tochigi.jp":true,"shimotsuke.tochigi.jp":true,"shioya.tochigi.jp":true,"takanezawa.tochigi.jp":true,"tochigi.tochigi.jp":true,"tsuga.tochigi.jp":true,"ujiie.tochigi.jp":true,"utsunomiya.tochigi.jp":true,"yaita.tochigi.jp":true,"aizumi.tokushima.jp":true,"anan.tokushima.jp":true,"ichiba.tokushima.jp":true,"itano.tokushima.jp":true,"kainan.tokushima.jp":true,"komatsushima.tokushima.jp":true,"matsushige.tokushima.jp":true,"mima.tokushima.jp":true,"minami.tokushima.jp":true,"miyoshi.tokushima.jp":true,"mugi.tokushima.jp":true,"nakagawa.tokushima.jp":true,"naruto.tokushima.jp":true,"sanagochi.tokushima.jp":true,"shishikui.tokushima.jp":true,"tokushima.tokushima.jp":true,"wajiki.tokushima.jp":true,"adachi.tokyo.jp":true,"akiruno.tokyo.jp":true,"akishima.tokyo.jp":true,"aogashima.tokyo.jp":true,"arakawa.tokyo.jp":true,"bunkyo.tokyo.jp":true,"chiyoda.tokyo.jp":true,"chofu.tokyo.jp":true,"chuo.tokyo.jp":true,"edogawa.tokyo.jp":true,"fuchu.tokyo.jp":true,"fussa.tokyo.jp":true,"hachijo.tokyo.jp":true,"hachioji.tokyo.jp":true,"hamura.tokyo.jp":true,"higashikurume.tokyo.jp":true,"higashimurayama.tokyo.jp":true,"higashiyamato.tokyo.jp":true,"hino.tokyo.jp":true,"hinode.tokyo.jp":true,"hinohara.tokyo.jp":true,"inagi.tokyo.jp":true,"itabashi.tokyo.jp":true,"katsushika.tokyo.jp":true,"kita.tokyo.jp":true,"kiyose.tokyo.jp":true,"kodaira.tokyo.jp":true,"koganei.tokyo.jp":true,"kokubunji.tokyo.jp":true,"komae.tokyo.jp":true,"koto.tokyo.jp":true,"kouzushima.tokyo.jp":true,"kunitachi.tokyo.jp":true,"machida.tokyo.jp":true,"meguro.tokyo.jp":true,"minato.tokyo.jp":true,"mitaka.tokyo.jp":true,"mizuho.tokyo.jp":true,"musashimurayama.tokyo.jp":true,"musashino.tokyo.jp":true,"nakano.tokyo.jp":true,"nerima.tokyo.jp":true,"ogasawara.tokyo.jp":true,"okutama.tokyo.jp":true,"ome.tokyo.jp":true,"oshima.tokyo.jp":true,"ota.tokyo.jp":true,"setagaya.tokyo.jp":true,"shibuya.tokyo.jp":true,"shinagawa.tokyo.jp":true,"shinjuku.tokyo.jp":true,"suginami.tokyo.jp":true,"sumida.tokyo.jp":true,"tachikawa.tokyo.jp":true,"taito.tokyo.jp":true,"tama.tokyo.jp":true,"toshima.tokyo.jp":true,"chizu.tottori.jp":true,"hino.tottori.jp":true,"kawahara.tottori.jp":true,"koge.tottori.jp":true,"kotoura.tottori.jp":true,"misasa.tottori.jp":true,"nanbu.tottori.jp":true,"nichinan.tottori.jp":true,"sakaiminato.tottori.jp":true,"tottori.tottori.jp":true,"wakasa.tottori.jp":true,"yazu.tottori.jp":true,"yonago.tottori.jp":true,"asahi.toyama.jp":true,"fuchu.toyama.jp":true,"fukumitsu.toyama.jp":true,"funahashi.toyama.jp":true,"himi.toyama.jp":true,"imizu.toyama.jp":true,"inami.toyama.jp":true,"johana.toyama.jp":true,"kamiichi.toyama.jp":true,"kurobe.toyama.jp":true,"nakaniikawa.toyama.jp":true,"namerikawa.toyama.jp":true,"nanto.toyama.jp":true,"nyuzen.toyama.jp":true,"oyabe.toyama.jp":true,"taira.toyama.jp":true,"takaoka.toyama.jp":true,"tateyama.toyama.jp":true,"toga.toyama.jp":true,"tonami.toyama.jp":true,"toyama.toyama.jp":true,"unazuki.toyama.jp":true,"uozu.toyama.jp":true,"yamada.toyama.jp":true,"arida.wakayama.jp":true,"aridagawa.wakayama.jp":true,"gobo.wakayama.jp":true,"hashimoto.wakayama.jp":true,"hidaka.wakayama.jp":true,"hirogawa.wakayama.jp":true,"inami.wakayama.jp":true,"iwade.wakayama.jp":true,"kainan.wakayama.jp":true,"kamitonda.wakayama.jp":true,"katsuragi.wakayama.jp":true,"kimino.wakayama.jp":true,"kinokawa.wakayama.jp":true,"kitayama.wakayama.jp":true,"koya.wakayama.jp":true,"koza.wakayama.jp":true,"kozagawa.wakayama.jp":true,"kudoyama.wakayama.jp":true,"kushimoto.wakayama.jp":true,"mihama.wakayama.jp":true,"misato.wakayama.jp":true,"nachikatsuura.wakayama.jp":true,"shingu.wakayama.jp":true,"shirahama.wakayama.jp":true,"taiji.wakayama.jp":true,"tanabe.wakayama.jp":true,"wakayama.wakayama.jp":true,"yuasa.wakayama.jp":true,"yura.wakayama.jp":true,"asahi.yamagata.jp":true,"funagata.yamagata.jp":true,"higashine.yamagata.jp":true,"iide.yamagata.jp":true,"kahoku.yamagata.jp":true,"kaminoyama.yamagata.jp":true,"kaneyama.yamagata.jp":true,"kawanishi.yamagata.jp":true,"mamurogawa.yamagata.jp":true,"mikawa.yamagata.jp":true,"murayama.yamagata.jp":true,"nagai.yamagata.jp":true,"nakayama.yamagata.jp":true,"nanyo.yamagata.jp":true,"nishikawa.yamagata.jp":true,"obanazawa.yamagata.jp":true,"oe.yamagata.jp":true,"oguni.yamagata.jp":true,"ohkura.yamagata.jp":true,"oishida.yamagata.jp":true,"sagae.yamagata.jp":true,"sakata.yamagata.jp":true,"sakegawa.yamagata.jp":true,"shinjo.yamagata.jp":true,"shirataka.yamagata.jp":true,"shonai.yamagata.jp":true,"takahata.yamagata.jp":true,"tendo.yamagata.jp":true,"tozawa.yamagata.jp":true,"tsuruoka.yamagata.jp":true,"yamagata.yamagata.jp":true,"yamanobe.yamagata.jp":true,"yonezawa.yamagata.jp":true,"yuza.yamagata.jp":true,"abu.yamaguchi.jp":true,"hagi.yamaguchi.jp":true,"hikari.yamaguchi.jp":true,"hofu.yamaguchi.jp":true,"iwakuni.yamaguchi.jp":true,"kudamatsu.yamaguchi.jp":true,"mitou.yamaguchi.jp":true,"nagato.yamaguchi.jp":true,"oshima.yamaguchi.jp":true,"shimonoseki.yamaguchi.jp":true,"shunan.yamaguchi.jp":true,"tabuse.yamaguchi.jp":true,"tokuyama.yamaguchi.jp":true,"toyota.yamaguchi.jp":true,"ube.yamaguchi.jp":true,"yuu.yamaguchi.jp":true,"chuo.yamanashi.jp":true,"doshi.yamanashi.jp":true,"fuefuki.yamanashi.jp":true,"fujikawa.yamanashi.jp":true,"fujikawaguchiko.yamanashi.jp":true,"fujiyoshida.yamanashi.jp":true,"hayakawa.yamanashi.jp":true,"hokuto.yamanashi.jp":true,"ichikawamisato.yamanashi.jp":true,"kai.yamanashi.jp":true,"kofu.yamanashi.jp":true,"koshu.yamanashi.jp":true,"kosuge.yamanashi.jp":true,"minami-alps.yamanashi.jp":true,"minobu.yamanashi.jp":true,"nakamichi.yamanashi.jp":true,"nanbu.yamanashi.jp":true,"narusawa.yamanashi.jp":true,"nirasaki.yamanashi.jp":true,"nishikatsura.yamanashi.jp":true,"oshino.yamanashi.jp":true,"otsuki.yamanashi.jp":true,"showa.yamanashi.jp":true,"tabayama.yamanashi.jp":true,"tsuru.yamanashi.jp":true,"uenohara.yamanashi.jp":true,"yamanakako.yamanashi.jp":true,"yamanashi.yamanashi.jp":true,"*.ke":true,"kg":true,"org.kg":true,"net.kg":true,"com.kg":true,"edu.kg":true,"gov.kg":true,"mil.kg":true,"*.kh":true,"ki":true,"edu.ki":true,"biz.ki":true,"net.ki":true,"org.ki":true,"gov.ki":true,"info.ki":true,"com.ki":true,"km":true,"org.km":true,"nom.km":true,"gov.km":true,"prd.km":true,"tm.km":true,"edu.km":true,"mil.km":true,"ass.km":true,"com.km":true,"coop.km":true,"asso.km":true,"presse.km":true,"medecin.km":true,"notaires.km":true,"pharmaciens.km":true,"veterinaire.km":true,"gouv.km":true,"kn":true,"net.kn":true,"org.kn":true,"edu.kn":true,"gov.kn":true,"kp":true,"com.kp":true,"edu.kp":true,"gov.kp":true,"org.kp":true,"rep.kp":true,"tra.kp":true,"kr":true,"ac.kr":true,"co.kr":true,"es.kr":true,"go.kr":true,"hs.kr":true,"kg.kr":true,"mil.kr":true,"ms.kr":true,"ne.kr":true,"or.kr":true,"pe.kr":true,"re.kr":true,"sc.kr":true,"busan.kr":true,"chungbuk.kr":true,"chungnam.kr":true,"daegu.kr":true,"daejeon.kr":true,"gangwon.kr":true,"gwangju.kr":true,"gyeongbuk.kr":true,"gyeonggi.kr":true,"gyeongnam.kr":true,"incheon.kr":true,"jeju.kr":true,"jeonbuk.kr":true,"jeonnam.kr":true,"seoul.kr":true,"ulsan.kr":true,"*.kw":true,"ky":true,"edu.ky":true,"gov.ky":true,"com.ky":true,"org.ky":true,"net.ky":true,"kz":true,"org.kz":true,"edu.kz":true,"net.kz":true,"gov.kz":true,"mil.kz":true,"com.kz":true,"la":true,"int.la":true,"net.la":true,"info.la":true,"edu.la":true,"gov.la":true,"per.la":true,"com.la":true,"org.la":true,"lb":true,"com.lb":true,"edu.lb":true,"gov.lb":true,"net.lb":true,"org.lb":true,"lc":true,"com.lc":true,"net.lc":true,"co.lc":true,"org.lc":true,"edu.lc":true,"gov.lc":true,"li":true,"lk":true,"gov.lk":true,"sch.lk":true,"net.lk":true,"int.lk":true,"com.lk":true,"org.lk":true,"edu.lk":true,"ngo.lk":true,"soc.lk":true,"web.lk":true,"ltd.lk":true,"assn.lk":true,"grp.lk":true,"hotel.lk":true,"ac.lk":true,"lr":true,"com.lr":true,"edu.lr":true,"gov.lr":true,"org.lr":true,"net.lr":true,"ls":true,"co.ls":true,"org.ls":true,"lt":true,"gov.lt":true,"lu":true,"lv":true,"com.lv":true,"edu.lv":true,"gov.lv":true,"org.lv":true,"mil.lv":true,"id.lv":true,"net.lv":true,"asn.lv":true,"conf.lv":true,"ly":true,"com.ly":true,"net.ly":true,"gov.ly":true,"plc.ly":true,"edu.ly":true,"sch.ly":true,"med.ly":true,"org.ly":true,"id.ly":true,"ma":true,"co.ma":true,"net.ma":true,"gov.ma":true,"org.ma":true,"ac.ma":true,"press.ma":true,"mc":true,"tm.mc":true,"asso.mc":true,"md":true,"me":true,"co.me":true,"net.me":true,"org.me":true,"edu.me":true,"ac.me":true,"gov.me":true,"its.me":true,"priv.me":true,"mg":true,"org.mg":true,"nom.mg":true,"gov.mg":true,"prd.mg":true,"tm.mg":true,"edu.mg":true,"mil.mg":true,"com.mg":true,"co.mg":true,"mh":true,"mil":true,"mk":true,"com.mk":true,"org.mk":true,"net.mk":true,"edu.mk":true,"gov.mk":true,"inf.mk":true,"name.mk":true,"ml":true,"com.ml":true,"edu.ml":true,"gouv.ml":true,"gov.ml":true,"net.ml":true,"org.ml":true,"presse.ml":true,"*.mm":true,"mn":true,"gov.mn":true,"edu.mn":true,"org.mn":true,"mo":true,"com.mo":true,"net.mo":true,"org.mo":true,"edu.mo":true,"gov.mo":true,"mobi":true,"mp":true,"mq":true,"mr":true,"gov.mr":true,"ms":true,"com.ms":true,"edu.ms":true,"gov.ms":true,"net.ms":true,"org.ms":true,"mt":true,"com.mt":true,"edu.mt":true,"net.mt":true,"org.mt":true,"mu":true,"com.mu":true,"net.mu":true,"org.mu":true,"gov.mu":true,"ac.mu":true,"co.mu":true,"or.mu":true,"museum":true,"academy.museum":true,"agriculture.museum":true,"air.museum":true,"airguard.museum":true,"alabama.museum":true,"alaska.museum":true,"amber.museum":true,"ambulance.museum":true,"american.museum":true,"americana.museum":true,"americanantiques.museum":true,"americanart.museum":true,"amsterdam.museum":true,"and.museum":true,"annefrank.museum":true,"anthro.museum":true,"anthropology.museum":true,"antiques.museum":true,"aquarium.museum":true,"arboretum.museum":true,"archaeological.museum":true,"archaeology.museum":true,"architecture.museum":true,"art.museum":true,"artanddesign.museum":true,"artcenter.museum":true,"artdeco.museum":true,"arteducation.museum":true,"artgallery.museum":true,"arts.museum":true,"artsandcrafts.museum":true,"asmatart.museum":true,"assassination.museum":true,"assisi.museum":true,"association.museum":true,"astronomy.museum":true,"atlanta.museum":true,"austin.museum":true,"australia.museum":true,"automotive.museum":true,"aviation.museum":true,"axis.museum":true,"badajoz.museum":true,"baghdad.museum":true,"bahn.museum":true,"bale.museum":true,"baltimore.museum":true,"barcelona.museum":true,"baseball.museum":true,"basel.museum":true,"baths.museum":true,"bauern.museum":true,"beauxarts.museum":true,"beeldengeluid.museum":true,"bellevue.museum":true,"bergbau.museum":true,"berkeley.museum":true,"berlin.museum":true,"bern.museum":true,"bible.museum":true,"bilbao.museum":true,"bill.museum":true,"birdart.museum":true,"birthplace.museum":true,"bonn.museum":true,"boston.museum":true,"botanical.museum":true,"botanicalgarden.museum":true,"botanicgarden.museum":true,"botany.museum":true,"brandywinevalley.museum":true,"brasil.museum":true,"bristol.museum":true,"british.museum":true,"britishcolumbia.museum":true,"broadcast.museum":true,"brunel.museum":true,"brussel.museum":true,"brussels.museum":true,"bruxelles.museum":true,"building.museum":true,"burghof.museum":true,"bus.museum":true,"bushey.museum":true,"cadaques.museum":true,"california.museum":true,"cambridge.museum":true,"can.museum":true,"canada.museum":true,"capebreton.museum":true,"carrier.museum":true,"cartoonart.museum":true,"casadelamoneda.museum":true,"castle.museum":true,"castres.museum":true,"celtic.museum":true,"center.museum":true,"chattanooga.museum":true,"cheltenham.museum":true,"chesapeakebay.museum":true,"chicago.museum":true,"children.museum":true,"childrens.museum":true,"childrensgarden.museum":true,"chiropractic.museum":true,"chocolate.museum":true,"christiansburg.museum":true,"cincinnati.museum":true,"cinema.museum":true,"circus.museum":true,"civilisation.museum":true,"civilization.museum":true,"civilwar.museum":true,"clinton.museum":true,"clock.museum":true,"coal.museum":true,"coastaldefence.museum":true,"cody.museum":true,"coldwar.museum":true,"collection.museum":true,"colonialwilliamsburg.museum":true,"coloradoplateau.museum":true,"columbia.museum":true,"columbus.museum":true,"communication.museum":true,"communications.museum":true,"community.museum":true,"computer.museum":true,"computerhistory.museum":true,"xn--comunicaes-v6a2o.museum":true,"contemporary.museum":true,"contemporaryart.museum":true,"convent.museum":true,"copenhagen.museum":true,"corporation.museum":true,"xn--correios-e-telecomunicaes-ghc29a.museum":true,"corvette.museum":true,"costume.museum":true,"countryestate.museum":true,"county.museum":true,"crafts.museum":true,"cranbrook.museum":true,"creation.museum":true,"cultural.museum":true,"culturalcenter.museum":true,"culture.museum":true,"cyber.museum":true,"cymru.museum":true,"dali.museum":true,"dallas.museum":true,"database.museum":true,"ddr.museum":true,"decorativearts.museum":true,"delaware.museum":true,"delmenhorst.museum":true,"denmark.museum":true,"depot.museum":true,"design.museum":true,"detroit.museum":true,"dinosaur.museum":true,"discovery.museum":true,"dolls.museum":true,"donostia.museum":true,"durham.museum":true,"eastafrica.museum":true,"eastcoast.museum":true,"education.museum":true,"educational.museum":true,"egyptian.museum":true,"eisenbahn.museum":true,"elburg.museum":true,"elvendrell.museum":true,"embroidery.museum":true,"encyclopedic.museum":true,"england.museum":true,"entomology.museum":true,"environment.museum":true,"environmentalconservation.museum":true,"epilepsy.museum":true,"essex.museum":true,"estate.museum":true,"ethnology.museum":true,"exeter.museum":true,"exhibition.museum":true,"family.museum":true,"farm.museum":true,"farmequipment.museum":true,"farmers.museum":true,"farmstead.museum":true,"field.museum":true,"figueres.museum":true,"filatelia.museum":true,"film.museum":true,"fineart.museum":true,"finearts.museum":true,"finland.museum":true,"flanders.museum":true,"florida.museum":true,"force.museum":true,"fortmissoula.museum":true,"fortworth.museum":true,"foundation.museum":true,"francaise.museum":true,"frankfurt.museum":true,"franziskaner.museum":true,"freemasonry.museum":true,"freiburg.museum":true,"fribourg.museum":true,"frog.museum":true,"fundacio.museum":true,"furniture.museum":true,"gallery.museum":true,"garden.museum":true,"gateway.museum":true,"geelvinck.museum":true,"gemological.museum":true,"geology.museum":true,"georgia.museum":true,"giessen.museum":true,"glas.museum":true,"glass.museum":true,"gorge.museum":true,"grandrapids.museum":true,"graz.museum":true,"guernsey.museum":true,"halloffame.museum":true,"hamburg.museum":true,"handson.museum":true,"harvestcelebration.museum":true,"hawaii.museum":true,"health.museum":true,"heimatunduhren.museum":true,"hellas.museum":true,"helsinki.museum":true,"hembygdsforbund.museum":true,"heritage.museum":true,"histoire.museum":true,"historical.museum":true,"historicalsociety.museum":true,"historichouses.museum":true,"historisch.museum":true,"historisches.museum":true,"history.museum":true,"historyofscience.museum":true,"horology.museum":true,"house.museum":true,"humanities.museum":true,"illustration.museum":true,"imageandsound.museum":true,"indian.museum":true,"indiana.museum":true,"indianapolis.museum":true,"indianmarket.museum":true,"intelligence.museum":true,"interactive.museum":true,"iraq.museum":true,"iron.museum":true,"isleofman.museum":true,"jamison.museum":true,"jefferson.museum":true,"jerusalem.museum":true,"jewelry.museum":true,"jewish.museum":true,"jewishart.museum":true,"jfk.museum":true,"journalism.museum":true,"judaica.museum":true,"judygarland.museum":true,"juedisches.museum":true,"juif.museum":true,"karate.museum":true,"karikatur.museum":true,"kids.museum":true,"koebenhavn.museum":true,"koeln.museum":true,"kunst.museum":true,"kunstsammlung.museum":true,"kunstunddesign.museum":true,"labor.museum":true,"labour.museum":true,"lajolla.museum":true,"lancashire.museum":true,"landes.museum":true,"lans.museum":true,"xn--lns-qla.museum":true,"larsson.museum":true,"lewismiller.museum":true,"lincoln.museum":true,"linz.museum":true,"living.museum":true,"livinghistory.museum":true,"localhistory.museum":true,"london.museum":true,"losangeles.museum":true,"louvre.museum":true,"loyalist.museum":true,"lucerne.museum":true,"luxembourg.museum":true,"luzern.museum":true,"mad.museum":true,"madrid.museum":true,"mallorca.museum":true,"manchester.museum":true,"mansion.museum":true,"mansions.museum":true,"manx.museum":true,"marburg.museum":true,"maritime.museum":true,"maritimo.museum":true,"maryland.museum":true,"marylhurst.museum":true,"media.museum":true,"medical.museum":true,"medizinhistorisches.museum":true,"meeres.museum":true,"memorial.museum":true,"mesaverde.museum":true,"michigan.museum":true,"midatlantic.museum":true,"military.museum":true,"mill.museum":true,"miners.museum":true,"mining.museum":true,"minnesota.museum":true,"missile.museum":true,"missoula.museum":true,"modern.museum":true,"moma.museum":true,"money.museum":true,"monmouth.museum":true,"monticello.museum":true,"montreal.museum":true,"moscow.museum":true,"motorcycle.museum":true,"muenchen.museum":true,"muenster.museum":true,"mulhouse.museum":true,"muncie.museum":true,"museet.museum":true,"museumcenter.museum":true,"museumvereniging.museum":true,"music.museum":true,"national.museum":true,"nationalfirearms.museum":true,"nationalheritage.museum":true,"nativeamerican.museum":true,"naturalhistory.museum":true,"naturalhistorymuseum.museum":true,"naturalsciences.museum":true,"nature.museum":true,"naturhistorisches.museum":true,"natuurwetenschappen.museum":true,"naumburg.museum":true,"naval.museum":true,"nebraska.museum":true,"neues.museum":true,"newhampshire.museum":true,"newjersey.museum":true,"newmexico.museum":true,"newport.museum":true,"newspaper.museum":true,"newyork.museum":true,"niepce.museum":true,"norfolk.museum":true,"north.museum":true,"nrw.museum":true,"nuernberg.museum":true,"nuremberg.museum":true,"nyc.museum":true,"nyny.museum":true,"oceanographic.museum":true,"oceanographique.museum":true,"omaha.museum":true,"online.museum":true,"ontario.museum":true,"openair.museum":true,"oregon.museum":true,"oregontrail.museum":true,"otago.museum":true,"oxford.museum":true,"pacific.museum":true,"paderborn.museum":true,"palace.museum":true,"paleo.museum":true,"palmsprings.museum":true,"panama.museum":true,"paris.museum":true,"pasadena.museum":true,"pharmacy.museum":true,"philadelphia.museum":true,"philadelphiaarea.museum":true,"philately.museum":true,"phoenix.museum":true,"photography.museum":true,"pilots.museum":true,"pittsburgh.museum":true,"planetarium.museum":true,"plantation.museum":true,"plants.museum":true,"plaza.museum":true,"portal.museum":true,"portland.museum":true,"portlligat.museum":true,"posts-and-telecommunications.museum":true,"preservation.museum":true,"presidio.museum":true,"press.museum":true,"project.museum":true,"public.museum":true,"pubol.museum":true,"quebec.museum":true,"railroad.museum":true,"railway.museum":true,"research.museum":true,"resistance.museum":true,"riodejaneiro.museum":true,"rochester.museum":true,"rockart.museum":true,"roma.museum":true,"russia.museum":true,"saintlouis.museum":true,"salem.museum":true,"salvadordali.museum":true,"salzburg.museum":true,"sandiego.museum":true,"sanfrancisco.museum":true,"santabarbara.museum":true,"santacruz.museum":true,"santafe.museum":true,"saskatchewan.museum":true,"satx.museum":true,"savannahga.museum":true,"schlesisches.museum":true,"schoenbrunn.museum":true,"schokoladen.museum":true,"school.museum":true,"schweiz.museum":true,"science.museum":true,"scienceandhistory.museum":true,"scienceandindustry.museum":true,"sciencecenter.museum":true,"sciencecenters.museum":true,"science-fiction.museum":true,"sciencehistory.museum":true,"sciences.museum":true,"sciencesnaturelles.museum":true,"scotland.museum":true,"seaport.museum":true,"settlement.museum":true,"settlers.museum":true,"shell.museum":true,"sherbrooke.museum":true,"sibenik.museum":true,"silk.museum":true,"ski.museum":true,"skole.museum":true,"society.museum":true,"sologne.museum":true,"soundandvision.museum":true,"southcarolina.museum":true,"southwest.museum":true,"space.museum":true,"spy.museum":true,"square.museum":true,"stadt.museum":true,"stalbans.museum":true,"starnberg.museum":true,"state.museum":true,"stateofdelaware.museum":true,"station.museum":true,"steam.museum":true,"steiermark.museum":true,"stjohn.museum":true,"stockholm.museum":true,"stpetersburg.museum":true,"stuttgart.museum":true,"suisse.museum":true,"surgeonshall.museum":true,"surrey.museum":true,"svizzera.museum":true,"sweden.museum":true,"sydney.museum":true,"tank.museum":true,"tcm.museum":true,"technology.museum":true,"telekommunikation.museum":true,"television.museum":true,"texas.museum":true,"textile.museum":true,"theater.museum":true,"time.museum":true,"timekeeping.museum":true,"topology.museum":true,"torino.museum":true,"touch.museum":true,"town.museum":true,"transport.museum":true,"tree.museum":true,"trolley.museum":true,"trust.museum":true,"trustee.museum":true,"uhren.museum":true,"ulm.museum":true,"undersea.museum":true,"university.museum":true,"usa.museum":true,"usantiques.museum":true,"usarts.museum":true,"uscountryestate.museum":true,"usculture.museum":true,"usdecorativearts.museum":true,"usgarden.museum":true,"ushistory.museum":true,"ushuaia.museum":true,"uslivinghistory.museum":true,"utah.museum":true,"uvic.museum":true,"valley.museum":true,"vantaa.museum":true,"versailles.museum":true,"viking.museum":true,"village.museum":true,"virginia.museum":true,"virtual.museum":true,"virtuel.museum":true,"vlaanderen.museum":true,"volkenkunde.museum":true,"wales.museum":true,"wallonie.museum":true,"war.museum":true,"washingtondc.museum":true,"watchandclock.museum":true,"watch-and-clock.museum":true,"western.museum":true,"westfalen.museum":true,"whaling.museum":true,"wildlife.museum":true,"williamsburg.museum":true,"windmill.museum":true,"workshop.museum":true,"york.museum":true,"yorkshire.museum":true,"yosemite.museum":true,"youth.museum":true,"zoological.museum":true,"zoology.museum":true,"xn--9dbhblg6di.museum":true,"xn--h1aegh.museum":true,"mv":true,"aero.mv":true,"biz.mv":true,"com.mv":true,"coop.mv":true,"edu.mv":true,"gov.mv":true,"info.mv":true,"int.mv":true,"mil.mv":true,"museum.mv":true,"name.mv":true,"net.mv":true,"org.mv":true,"pro.mv":true,"mw":true,"ac.mw":true,"biz.mw":true,"co.mw":true,"com.mw":true,"coop.mw":true,"edu.mw":true,"gov.mw":true,"int.mw":true,"museum.mw":true,"net.mw":true,"org.mw":true,"mx":true,"com.mx":true,"org.mx":true,"gob.mx":true,"edu.mx":true,"net.mx":true,"my":true,"com.my":true,"net.my":true,"org.my":true,"gov.my":true,"edu.my":true,"mil.my":true,"name.my":true,"*.mz":true,"teledata.mz":false,"na":true,"info.na":true,"pro.na":true,"name.na":true,"school.na":true,"or.na":true,"dr.na":true,"us.na":true,"mx.na":true,"ca.na":true,"in.na":true,"cc.na":true,"tv.na":true,"ws.na":true,"mobi.na":true,"co.na":true,"com.na":true,"org.na":true,"name":true,"nc":true,"asso.nc":true,"ne":true,"net":true,"nf":true,"com.nf":true,"net.nf":true,"per.nf":true,"rec.nf":true,"web.nf":true,"arts.nf":true,"firm.nf":true,"info.nf":true,"other.nf":true,"store.nf":true,"ng":true,"com.ng":true,"edu.ng":true,"name.ng":true,"net.ng":true,"org.ng":true,"sch.ng":true,"gov.ng":true,"mil.ng":true,"mobi.ng":true,"*.ni":true,"nl":true,"bv.nl":true,"no":true,"fhs.no":true,"vgs.no":true,"fylkesbibl.no":true,"folkebibl.no":true,"museum.no":true,"idrett.no":true,"priv.no":true,"mil.no":true,"stat.no":true,"dep.no":true,"kommune.no":true,"herad.no":true,"aa.no":true,"ah.no":true,"bu.no":true,"fm.no":true,"hl.no":true,"hm.no":true,"jan-mayen.no":true,"mr.no":true,"nl.no":true,"nt.no":true,"of.no":true,"ol.no":true,"oslo.no":true,"rl.no":true,"sf.no":true,"st.no":true,"svalbard.no":true,"tm.no":true,"tr.no":true,"va.no":true,"vf.no":true,"gs.aa.no":true,"gs.ah.no":true,"gs.bu.no":true,"gs.fm.no":true,"gs.hl.no":true,"gs.hm.no":true,"gs.jan-mayen.no":true,"gs.mr.no":true,"gs.nl.no":true,"gs.nt.no":true,"gs.of.no":true,"gs.ol.no":true,"gs.oslo.no":true,"gs.rl.no":true,"gs.sf.no":true,"gs.st.no":true,"gs.svalbard.no":true,"gs.tm.no":true,"gs.tr.no":true,"gs.va.no":true,"gs.vf.no":true,"akrehamn.no":true,"xn--krehamn-dxa.no":true,"algard.no":true,"xn--lgrd-poac.no":true,"arna.no":true,"brumunddal.no":true,"bryne.no":true,"bronnoysund.no":true,"xn--brnnysund-m8ac.no":true,"drobak.no":true,"xn--drbak-wua.no":true,"egersund.no":true,"fetsund.no":true,"floro.no":true,"xn--flor-jra.no":true,"fredrikstad.no":true,"hokksund.no":true,"honefoss.no":true,"xn--hnefoss-q1a.no":true,"jessheim.no":true,"jorpeland.no":true,"xn--jrpeland-54a.no":true,"kirkenes.no":true,"kopervik.no":true,"krokstadelva.no":true,"langevag.no":true,"xn--langevg-jxa.no":true,"leirvik.no":true,"mjondalen.no":true,"xn--mjndalen-64a.no":true,"mo-i-rana.no":true,"mosjoen.no":true,"xn--mosjen-eya.no":true,"nesoddtangen.no":true,"orkanger.no":true,"osoyro.no":true,"xn--osyro-wua.no":true,"raholt.no":true,"xn--rholt-mra.no":true,"sandnessjoen.no":true,"xn--sandnessjen-ogb.no":true,"skedsmokorset.no":true,"slattum.no":true,"spjelkavik.no":true,"stathelle.no":true,"stavern.no":true,"stjordalshalsen.no":true,"xn--stjrdalshalsen-sqb.no":true,"tananger.no":true,"tranby.no":true,"vossevangen.no":true,"afjord.no":true,"xn--fjord-lra.no":true,"agdenes.no":true,"al.no":true,"xn--l-1fa.no":true,"alesund.no":true,"xn--lesund-hua.no":true,"alstahaug.no":true,"alta.no":true,"xn--lt-liac.no":true,"alaheadju.no":true,"xn--laheadju-7ya.no":true,"alvdal.no":true,"amli.no":true,"xn--mli-tla.no":true,"amot.no":true,"xn--mot-tla.no":true,"andebu.no":true,"andoy.no":true,"xn--andy-ira.no":true,"andasuolo.no":true,"ardal.no":true,"xn--rdal-poa.no":true,"aremark.no":true,"arendal.no":true,"xn--s-1fa.no":true,"aseral.no":true,"xn--seral-lra.no":true,"asker.no":true,"askim.no":true,"askvoll.no":true,"askoy.no":true,"xn--asky-ira.no":true,"asnes.no":true,"xn--snes-poa.no":true,"audnedaln.no":true,"aukra.no":true,"aure.no":true,"aurland.no":true,"aurskog-holand.no":true,"xn--aurskog-hland-jnb.no":true,"austevoll.no":true,"austrheim.no":true,"averoy.no":true,"xn--avery-yua.no":true,"balestrand.no":true,"ballangen.no":true,"balat.no":true,"xn--blt-elab.no":true,"balsfjord.no":true,"bahccavuotna.no":true,"xn--bhccavuotna-k7a.no":true,"bamble.no":true,"bardu.no":true,"beardu.no":true,"beiarn.no":true,"bajddar.no":true,"xn--bjddar-pta.no":true,"baidar.no":true,"xn--bidr-5nac.no":true,"berg.no":true,"bergen.no":true,"berlevag.no":true,"xn--berlevg-jxa.no":true,"bearalvahki.no":true,"xn--bearalvhki-y4a.no":true,"bindal.no":true,"birkenes.no":true,"bjarkoy.no":true,"xn--bjarky-fya.no":true,"bjerkreim.no":true,"bjugn.no":true,"bodo.no":true,"xn--bod-2na.no":true,"badaddja.no":true,"xn--bdddj-mrabd.no":true,"budejju.no":true,"bokn.no":true,"bremanger.no":true,"bronnoy.no":true,"xn--brnny-wuac.no":true,"bygland.no":true,"bykle.no":true,"barum.no":true,"xn--brum-voa.no":true,"bo.telemark.no":true,"xn--b-5ga.telemark.no":true,"bo.nordland.no":true,"xn--b-5ga.nordland.no":true,"bievat.no":true,"xn--bievt-0qa.no":true,"bomlo.no":true,"xn--bmlo-gra.no":true,"batsfjord.no":true,"xn--btsfjord-9za.no":true,"bahcavuotna.no":true,"xn--bhcavuotna-s4a.no":true,"dovre.no":true,"drammen.no":true,"drangedal.no":true,"dyroy.no":true,"xn--dyry-ira.no":true,"donna.no":true,"xn--dnna-gra.no":true,"eid.no":true,"eidfjord.no":true,"eidsberg.no":true,"eidskog.no":true,"eidsvoll.no":true,"eigersund.no":true,"elverum.no":true,"enebakk.no":true,"engerdal.no":true,"etne.no":true,"etnedal.no":true,"evenes.no":true,"evenassi.no":true,"xn--eveni-0qa01ga.no":true,"evje-og-hornnes.no":true,"farsund.no":true,"fauske.no":true,"fuossko.no":true,"fuoisku.no":true,"fedje.no":true,"fet.no":true,"finnoy.no":true,"xn--finny-yua.no":true,"fitjar.no":true,"fjaler.no":true,"fjell.no":true,"flakstad.no":true,"flatanger.no":true,"flekkefjord.no":true,"flesberg.no":true,"flora.no":true,"fla.no":true,"xn--fl-zia.no":true,"folldal.no":true,"forsand.no":true,"fosnes.no":true,"frei.no":true,"frogn.no":true,"froland.no":true,"frosta.no":true,"frana.no":true,"xn--frna-woa.no":true,"froya.no":true,"xn--frya-hra.no":true,"fusa.no":true,"fyresdal.no":true,"forde.no":true,"xn--frde-gra.no":true,"gamvik.no":true,"gangaviika.no":true,"xn--ggaviika-8ya47h.no":true,"gaular.no":true,"gausdal.no":true,"gildeskal.no":true,"xn--gildeskl-g0a.no":true,"giske.no":true,"gjemnes.no":true,"gjerdrum.no":true,"gjerstad.no":true,"gjesdal.no":true,"gjovik.no":true,"xn--gjvik-wua.no":true,"gloppen.no":true,"gol.no":true,"gran.no":true,"grane.no":true,"granvin.no":true,"gratangen.no":true,"grimstad.no":true,"grong.no":true,"kraanghke.no":true,"xn--kranghke-b0a.no":true,"grue.no":true,"gulen.no":true,"hadsel.no":true,"halden.no":true,"halsa.no":true,"hamar.no":true,"hamaroy.no":true,"habmer.no":true,"xn--hbmer-xqa.no":true,"hapmir.no":true,"xn--hpmir-xqa.no":true,"hammerfest.no":true,"hammarfeasta.no":true,"xn--hmmrfeasta-s4ac.no":true,"haram.no":true,"hareid.no":true,"harstad.no":true,"hasvik.no":true,"aknoluokta.no":true,"xn--koluokta-7ya57h.no":true,"hattfjelldal.no":true,"aarborte.no":true,"haugesund.no":true,"hemne.no":true,"hemnes.no":true,"hemsedal.no":true,"heroy.more-og-romsdal.no":true,"xn--hery-ira.xn--mre-og-romsdal-qqb.no":true,"heroy.nordland.no":true,"xn--hery-ira.nordland.no":true,"hitra.no":true,"hjartdal.no":true,"hjelmeland.no":true,"hobol.no":true,"xn--hobl-ira.no":true,"hof.no":true,"hol.no":true,"hole.no":true,"holmestrand.no":true,"holtalen.no":true,"xn--holtlen-hxa.no":true,"hornindal.no":true,"horten.no":true,"hurdal.no":true,"hurum.no":true,"hvaler.no":true,"hyllestad.no":true,"hagebostad.no":true,"xn--hgebostad-g3a.no":true,"hoyanger.no":true,"xn--hyanger-q1a.no":true,"hoylandet.no":true,"xn--hylandet-54a.no":true,"ha.no":true,"xn--h-2fa.no":true,"ibestad.no":true,"inderoy.no":true,"xn--indery-fya.no":true,"iveland.no":true,"jevnaker.no":true,"jondal.no":true,"jolster.no":true,"xn--jlster-bya.no":true,"karasjok.no":true,"karasjohka.no":true,"xn--krjohka-hwab49j.no":true,"karlsoy.no":true,"galsa.no":true,"xn--gls-elac.no":true,"karmoy.no":true,"xn--karmy-yua.no":true,"kautokeino.no":true,"guovdageaidnu.no":true,"klepp.no":true,"klabu.no":true,"xn--klbu-woa.no":true,"kongsberg.no":true,"kongsvinger.no":true,"kragero.no":true,"xn--krager-gya.no":true,"kristiansand.no":true,"kristiansund.no":true,"krodsherad.no":true,"xn--krdsherad-m8a.no":true,"kvalsund.no":true,"rahkkeravju.no":true,"xn--rhkkervju-01af.no":true,"kvam.no":true,"kvinesdal.no":true,"kvinnherad.no":true,"kviteseid.no":true,"kvitsoy.no":true,"xn--kvitsy-fya.no":true,"kvafjord.no":true,"xn--kvfjord-nxa.no":true,"giehtavuoatna.no":true,"kvanangen.no":true,"xn--kvnangen-k0a.no":true,"navuotna.no":true,"xn--nvuotna-hwa.no":true,"kafjord.no":true,"xn--kfjord-iua.no":true,"gaivuotna.no":true,"xn--givuotna-8ya.no":true,"larvik.no":true,"lavangen.no":true,"lavagis.no":true,"loabat.no":true,"xn--loabt-0qa.no":true,"lebesby.no":true,"davvesiida.no":true,"leikanger.no":true,"leirfjord.no":true,"leka.no":true,"leksvik.no":true,"lenvik.no":true,"leangaviika.no":true,"xn--leagaviika-52b.no":true,"lesja.no":true,"levanger.no":true,"lier.no":true,"lierne.no":true,"lillehammer.no":true,"lillesand.no":true,"lindesnes.no":true,"lindas.no":true,"xn--linds-pra.no":true,"lom.no":true,"loppa.no":true,"lahppi.no":true,"xn--lhppi-xqa.no":true,"lund.no":true,"lunner.no":true,"luroy.no":true,"xn--lury-ira.no":true,"luster.no":true,"lyngdal.no":true,"lyngen.no":true,"ivgu.no":true,"lardal.no":true,"lerdal.no":true,"xn--lrdal-sra.no":true,"lodingen.no":true,"xn--ldingen-q1a.no":true,"lorenskog.no":true,"xn--lrenskog-54a.no":true,"loten.no":true,"xn--lten-gra.no":true,"malvik.no":true,"masoy.no":true,"xn--msy-ula0h.no":true,"muosat.no":true,"xn--muost-0qa.no":true,"mandal.no":true,"marker.no":true,"marnardal.no":true,"masfjorden.no":true,"meland.no":true,"meldal.no":true,"melhus.no":true,"meloy.no":true,"xn--mely-ira.no":true,"meraker.no":true,"xn--merker-kua.no":true,"moareke.no":true,"xn--moreke-jua.no":true,"midsund.no":true,"midtre-gauldal.no":true,"modalen.no":true,"modum.no":true,"molde.no":true,"moskenes.no":true,"moss.no":true,"mosvik.no":true,"malselv.no":true,"xn--mlselv-iua.no":true,"malatvuopmi.no":true,"xn--mlatvuopmi-s4a.no":true,"namdalseid.no":true,"aejrie.no":true,"namsos.no":true,"namsskogan.no":true,"naamesjevuemie.no":true,"xn--nmesjevuemie-tcba.no":true,"laakesvuemie.no":true,"nannestad.no":true,"narvik.no":true,"narviika.no":true,"naustdal.no":true,"nedre-eiker.no":true,"nes.akershus.no":true,"nes.buskerud.no":true,"nesna.no":true,"nesodden.no":true,"nesseby.no":true,"unjarga.no":true,"xn--unjrga-rta.no":true,"nesset.no":true,"nissedal.no":true,"nittedal.no":true,"nord-aurdal.no":true,"nord-fron.no":true,"nord-odal.no":true,"norddal.no":true,"nordkapp.no":true,"davvenjarga.no":true,"xn--davvenjrga-y4a.no":true,"nordre-land.no":true,"nordreisa.no":true,"raisa.no":true,"xn--risa-5na.no":true,"nore-og-uvdal.no":true,"notodden.no":true,"naroy.no":true,"xn--nry-yla5g.no":true,"notteroy.no":true,"xn--nttery-byae.no":true,"odda.no":true,"oksnes.no":true,"xn--ksnes-uua.no":true,"oppdal.no":true,"oppegard.no":true,"xn--oppegrd-ixa.no":true,"orkdal.no":true,"orland.no":true,"xn--rland-uua.no":true,"orskog.no":true,"xn--rskog-uua.no":true,"orsta.no":true,"xn--rsta-fra.no":true,"os.hedmark.no":true,"os.hordaland.no":true,"osen.no":true,"osteroy.no":true,"xn--ostery-fya.no":true,"ostre-toten.no":true,"xn--stre-toten-zcb.no":true,"overhalla.no":true,"ovre-eiker.no":true,"xn--vre-eiker-k8a.no":true,"oyer.no":true,"xn--yer-zna.no":true,"oygarden.no":true,"xn--ygarden-p1a.no":true,"oystre-slidre.no":true,"xn--ystre-slidre-ujb.no":true,"porsanger.no":true,"porsangu.no":true,"xn--porsgu-sta26f.no":true,"porsgrunn.no":true,"radoy.no":true,"xn--rady-ira.no":true,"rakkestad.no":true,"rana.no":true,"ruovat.no":true,"randaberg.no":true,"rauma.no":true,"rendalen.no":true,"rennebu.no":true,"rennesoy.no":true,"xn--rennesy-v1a.no":true,"rindal.no":true,"ringebu.no":true,"ringerike.no":true,"ringsaker.no":true,"rissa.no":true,"risor.no":true,"xn--risr-ira.no":true,"roan.no":true,"rollag.no":true,"rygge.no":true,"ralingen.no":true,"xn--rlingen-mxa.no":true,"rodoy.no":true,"xn--rdy-0nab.no":true,"romskog.no":true,"xn--rmskog-bya.no":true,"roros.no":true,"xn--rros-gra.no":true,"rost.no":true,"xn--rst-0na.no":true,"royken.no":true,"xn--ryken-vua.no":true,"royrvik.no":true,"xn--ryrvik-bya.no":true,"rade.no":true,"xn--rde-ula.no":true,"salangen.no":true,"siellak.no":true,"saltdal.no":true,"salat.no":true,"xn--slt-elab.no":true,"xn--slat-5na.no":true,"samnanger.no":true,"sande.more-og-romsdal.no":true,"sande.xn--mre-og-romsdal-qqb.no":true,"sande.vestfold.no":true,"sandefjord.no":true,"sandnes.no":true,"sandoy.no":true,"xn--sandy-yua.no":true,"sarpsborg.no":true,"sauda.no":true,"sauherad.no":true,"sel.no":true,"selbu.no":true,"selje.no":true,"seljord.no":true,"sigdal.no":true,"siljan.no":true,"sirdal.no":true,"skaun.no":true,"skedsmo.no":true,"ski.no":true,"skien.no":true,"skiptvet.no":true,"skjervoy.no":true,"xn--skjervy-v1a.no":true,"skierva.no":true,"xn--skierv-uta.no":true,"skjak.no":true,"xn--skjk-soa.no":true,"skodje.no":true,"skanland.no":true,"xn--sknland-fxa.no":true,"skanit.no":true,"xn--sknit-yqa.no":true,"smola.no":true,"xn--smla-hra.no":true,"snillfjord.no":true,"snasa.no":true,"xn--snsa-roa.no":true,"snoasa.no":true,"snaase.no":true,"xn--snase-nra.no":true,"sogndal.no":true,"sokndal.no":true,"sola.no":true,"solund.no":true,"songdalen.no":true,"sortland.no":true,"spydeberg.no":true,"stange.no":true,"stavanger.no":true,"steigen.no":true,"steinkjer.no":true,"stjordal.no":true,"xn--stjrdal-s1a.no":true,"stokke.no":true,"stor-elvdal.no":true,"stord.no":true,"stordal.no":true,"storfjord.no":true,"omasvuotna.no":true,"strand.no":true,"stranda.no":true,"stryn.no":true,"sula.no":true,"suldal.no":true,"sund.no":true,"sunndal.no":true,"surnadal.no":true,"sveio.no":true,"svelvik.no":true,"sykkylven.no":true,"sogne.no":true,"xn--sgne-gra.no":true,"somna.no":true,"xn--smna-gra.no":true,"sondre-land.no":true,"xn--sndre-land-0cb.no":true,"sor-aurdal.no":true,"xn--sr-aurdal-l8a.no":true,"sor-fron.no":true,"xn--sr-fron-q1a.no":true,"sor-odal.no":true,"xn--sr-odal-q1a.no":true,"sor-varanger.no":true,"xn--sr-varanger-ggb.no":true,"matta-varjjat.no":true,"xn--mtta-vrjjat-k7af.no":true,"sorfold.no":true,"xn--srfold-bya.no":true,"sorreisa.no":true,"xn--srreisa-q1a.no":true,"sorum.no":true,"xn--srum-gra.no":true,"tana.no":true,"deatnu.no":true,"time.no":true,"tingvoll.no":true,"tinn.no":true,"tjeldsund.no":true,"dielddanuorri.no":true,"tjome.no":true,"xn--tjme-hra.no":true,"tokke.no":true,"tolga.no":true,"torsken.no":true,"tranoy.no":true,"xn--trany-yua.no":true,"tromso.no":true,"xn--troms-zua.no":true,"tromsa.no":true,"romsa.no":true,"trondheim.no":true,"troandin.no":true,"trysil.no":true,"trana.no":true,"xn--trna-woa.no":true,"trogstad.no":true,"xn--trgstad-r1a.no":true,"tvedestrand.no":true,"tydal.no":true,"tynset.no":true,"tysfjord.no":true,"divtasvuodna.no":true,"divttasvuotna.no":true,"tysnes.no":true,"tysvar.no":true,"xn--tysvr-vra.no":true,"tonsberg.no":true,"xn--tnsberg-q1a.no":true,"ullensaker.no":true,"ullensvang.no":true,"ulvik.no":true,"utsira.no":true,"vadso.no":true,"xn--vads-jra.no":true,"cahcesuolo.no":true,"xn--hcesuolo-7ya35b.no":true,"vaksdal.no":true,"valle.no":true,"vang.no":true,"vanylven.no":true,"vardo.no":true,"xn--vard-jra.no":true,"varggat.no":true,"xn--vrggt-xqad.no":true,"vefsn.no":true,"vaapste.no":true,"vega.no":true,"vegarshei.no":true,"xn--vegrshei-c0a.no":true,"vennesla.no":true,"verdal.no":true,"verran.no":true,"vestby.no":true,"vestnes.no":true,"vestre-slidre.no":true,"vestre-toten.no":true,"vestvagoy.no":true,"xn--vestvgy-ixa6o.no":true,"vevelstad.no":true,"vik.no":true,"vikna.no":true,"vindafjord.no":true,"volda.no":true,"voss.no":true,"varoy.no":true,"xn--vry-yla5g.no":true,"vagan.no":true,"xn--vgan-qoa.no":true,"voagat.no":true,"vagsoy.no":true,"xn--vgsy-qoa0j.no":true,"vaga.no":true,"xn--vg-yiab.no":true,"valer.ostfold.no":true,"xn--vler-qoa.xn--stfold-9xa.no":true,"valer.hedmark.no":true,"xn--vler-qoa.hedmark.no":true,"*.np":true,"nr":true,"biz.nr":true,"info.nr":true,"gov.nr":true,"edu.nr":true,"org.nr":true,"net.nr":true,"com.nr":true,"nu":true,"nz":true,"ac.nz":true,"co.nz":true,"cri.nz":true,"geek.nz":true,"gen.nz":true,"govt.nz":true,"health.nz":true,"iwi.nz":true,"kiwi.nz":true,"maori.nz":true,"mil.nz":true,"xn--mori-qsa.nz":true,"net.nz":true,"org.nz":true,"parliament.nz":true,"school.nz":true,"om":true,"co.om":true,"com.om":true,"edu.om":true,"gov.om":true,"med.om":true,"museum.om":true,"net.om":true,"org.om":true,"pro.om":true,"org":true,"pa":true,"ac.pa":true,"gob.pa":true,"com.pa":true,"org.pa":true,"sld.pa":true,"edu.pa":true,"net.pa":true,"ing.pa":true,"abo.pa":true,"med.pa":true,"nom.pa":true,"pe":true,"edu.pe":true,"gob.pe":true,"nom.pe":true,"mil.pe":true,"org.pe":true,"com.pe":true,"net.pe":true,"pf":true,"com.pf":true,"org.pf":true,"edu.pf":true,"*.pg":true,"ph":true,"com.ph":true,"net.ph":true,"org.ph":true,"gov.ph":true,"edu.ph":true,"ngo.ph":true,"mil.ph":true,"i.ph":true,"pk":true,"com.pk":true,"net.pk":true,"edu.pk":true,"org.pk":true,"fam.pk":true,"biz.pk":true,"web.pk":true,"gov.pk":true,"gob.pk":true,"gok.pk":true,"gon.pk":true,"gop.pk":true,"gos.pk":true,"info.pk":true,"pl":true,"com.pl":true,"net.pl":true,"org.pl":true,"aid.pl":true,"agro.pl":true,"atm.pl":true,"auto.pl":true,"biz.pl":true,"edu.pl":true,"gmina.pl":true,"gsm.pl":true,"info.pl":true,"mail.pl":true,"miasta.pl":true,"media.pl":true,"mil.pl":true,"nieruchomosci.pl":true,"nom.pl":true,"pc.pl":true,"powiat.pl":true,"priv.pl":true,"realestate.pl":true,"rel.pl":true,"sex.pl":true,"shop.pl":true,"sklep.pl":true,"sos.pl":true,"szkola.pl":true,"targi.pl":true,"tm.pl":true,"tourism.pl":true,"travel.pl":true,"turystyka.pl":true,"gov.pl":true,"ap.gov.pl":true,"ic.gov.pl":true,"is.gov.pl":true,"us.gov.pl":true,"kmpsp.gov.pl":true,"kppsp.gov.pl":true,"kwpsp.gov.pl":true,"psp.gov.pl":true,"wskr.gov.pl":true,"kwp.gov.pl":true,"mw.gov.pl":true,"ug.gov.pl":true,"um.gov.pl":true,"umig.gov.pl":true,"ugim.gov.pl":true,"upow.gov.pl":true,"uw.gov.pl":true,"starostwo.gov.pl":true,"pa.gov.pl":true,"po.gov.pl":true,"psse.gov.pl":true,"pup.gov.pl":true,"rzgw.gov.pl":true,"sa.gov.pl":true,"so.gov.pl":true,"sr.gov.pl":true,"wsa.gov.pl":true,"sko.gov.pl":true,"uzs.gov.pl":true,"wiih.gov.pl":true,"winb.gov.pl":true,"pinb.gov.pl":true,"wios.gov.pl":true,"witd.gov.pl":true,"wzmiuw.gov.pl":true,"piw.gov.pl":true,"wiw.gov.pl":true,"griw.gov.pl":true,"wif.gov.pl":true,"oum.gov.pl":true,"sdn.gov.pl":true,"zp.gov.pl":true,"uppo.gov.pl":true,"mup.gov.pl":true,"wuoz.gov.pl":true,"konsulat.gov.pl":true,"oirm.gov.pl":true,"augustow.pl":true,"babia-gora.pl":true,"bedzin.pl":true,"beskidy.pl":true,"bialowieza.pl":true,"bialystok.pl":true,"bielawa.pl":true,"bieszczady.pl":true,"boleslawiec.pl":true,"bydgoszcz.pl":true,"bytom.pl":true,"cieszyn.pl":true,"czeladz.pl":true,"czest.pl":true,"dlugoleka.pl":true,"elblag.pl":true,"elk.pl":true,"glogow.pl":true,"gniezno.pl":true,"gorlice.pl":true,"grajewo.pl":true,"ilawa.pl":true,"jaworzno.pl":true,"jelenia-gora.pl":true,"jgora.pl":true,"kalisz.pl":true,"kazimierz-dolny.pl":true,"karpacz.pl":true,"kartuzy.pl":true,"kaszuby.pl":true,"katowice.pl":true,"kepno.pl":true,"ketrzyn.pl":true,"klodzko.pl":true,"kobierzyce.pl":true,"kolobrzeg.pl":true,"konin.pl":true,"konskowola.pl":true,"kutno.pl":true,"lapy.pl":true,"lebork.pl":true,"legnica.pl":true,"lezajsk.pl":true,"limanowa.pl":true,"lomza.pl":true,"lowicz.pl":true,"lubin.pl":true,"lukow.pl":true,"malbork.pl":true,"malopolska.pl":true,"mazowsze.pl":true,"mazury.pl":true,"mielec.pl":true,"mielno.pl":true,"mragowo.pl":true,"naklo.pl":true,"nowaruda.pl":true,"nysa.pl":true,"olawa.pl":true,"olecko.pl":true,"olkusz.pl":true,"olsztyn.pl":true,"opoczno.pl":true,"opole.pl":true,"ostroda.pl":true,"ostroleka.pl":true,"ostrowiec.pl":true,"ostrowwlkp.pl":true,"pila.pl":true,"pisz.pl":true,"podhale.pl":true,"podlasie.pl":true,"polkowice.pl":true,"pomorze.pl":true,"pomorskie.pl":true,"prochowice.pl":true,"pruszkow.pl":true,"przeworsk.pl":true,"pulawy.pl":true,"radom.pl":true,"rawa-maz.pl":true,"rybnik.pl":true,"rzeszow.pl":true,"sanok.pl":true,"sejny.pl":true,"slask.pl":true,"slupsk.pl":true,"sosnowiec.pl":true,"stalowa-wola.pl":true,"skoczow.pl":true,"starachowice.pl":true,"stargard.pl":true,"suwalki.pl":true,"swidnica.pl":true,"swiebodzin.pl":true,"swinoujscie.pl":true,"szczecin.pl":true,"szczytno.pl":true,"tarnobrzeg.pl":true,"tgory.pl":true,"turek.pl":true,"tychy.pl":true,"ustka.pl":true,"walbrzych.pl":true,"warmia.pl":true,"warszawa.pl":true,"waw.pl":true,"wegrow.pl":true,"wielun.pl":true,"wlocl.pl":true,"wloclawek.pl":true,"wodzislaw.pl":true,"wolomin.pl":true,"wroclaw.pl":true,"zachpomor.pl":true,"zagan.pl":true,"zarow.pl":true,"zgora.pl":true,"zgorzelec.pl":true,"pm":true,"pn":true,"gov.pn":true,"co.pn":true,"org.pn":true,"edu.pn":true,"net.pn":true,"post":true,"pr":true,"com.pr":true,"net.pr":true,"org.pr":true,"gov.pr":true,"edu.pr":true,"isla.pr":true,"pro.pr":true,"biz.pr":true,"info.pr":true,"name.pr":true,"est.pr":true,"prof.pr":true,"ac.pr":true,"pro":true,"aca.pro":true,"bar.pro":true,"cpa.pro":true,"jur.pro":true,"law.pro":true,"med.pro":true,"eng.pro":true,"ps":true,"edu.ps":true,"gov.ps":true,"sec.ps":true,"plo.ps":true,"com.ps":true,"org.ps":true,"net.ps":true,"pt":true,"net.pt":true,"gov.pt":true,"org.pt":true,"edu.pt":true,"int.pt":true,"publ.pt":true,"com.pt":true,"nome.pt":true,"pw":true,"co.pw":true,"ne.pw":true,"or.pw":true,"ed.pw":true,"go.pw":true,"belau.pw":true,"py":true,"com.py":true,"coop.py":true,"edu.py":true,"gov.py":true,"mil.py":true,"net.py":true,"org.py":true,"qa":true,"com.qa":true,"edu.qa":true,"gov.qa":true,"mil.qa":true,"name.qa":true,"net.qa":true,"org.qa":true,"sch.qa":true,"re":true,"com.re":true,"asso.re":true,"nom.re":true,"ro":true,"com.ro":true,"org.ro":true,"tm.ro":true,"nt.ro":true,"nom.ro":true,"info.ro":true,"rec.ro":true,"arts.ro":true,"firm.ro":true,"store.ro":true,"www.ro":true,"rs":true,"co.rs":true,"org.rs":true,"edu.rs":true,"ac.rs":true,"gov.rs":true,"in.rs":true,"ru":true,"ac.ru":true,"com.ru":true,"edu.ru":true,"int.ru":true,"net.ru":true,"org.ru":true,"pp.ru":true,"adygeya.ru":true,"altai.ru":true,"amur.ru":true,"arkhangelsk.ru":true,"astrakhan.ru":true,"bashkiria.ru":true,"belgorod.ru":true,"bir.ru":true,"bryansk.ru":true,"buryatia.ru":true,"cbg.ru":true,"chel.ru":true,"chelyabinsk.ru":true,"chita.ru":true,"chukotka.ru":true,"chuvashia.ru":true,"dagestan.ru":true,"dudinka.ru":true,"e-burg.ru":true,"grozny.ru":true,"irkutsk.ru":true,"ivanovo.ru":true,"izhevsk.ru":true,"jar.ru":true,"joshkar-ola.ru":true,"kalmykia.ru":true,"kaluga.ru":true,"kamchatka.ru":true,"karelia.ru":true,"kazan.ru":true,"kchr.ru":true,"kemerovo.ru":true,"khabarovsk.ru":true,"khakassia.ru":true,"khv.ru":true,"kirov.ru":true,"koenig.ru":true,"komi.ru":true,"kostroma.ru":true,"krasnoyarsk.ru":true,"kuban.ru":true,"kurgan.ru":true,"kursk.ru":true,"lipetsk.ru":true,"magadan.ru":true,"mari.ru":true,"mari-el.ru":true,"marine.ru":true,"mordovia.ru":true,"msk.ru":true,"murmansk.ru":true,"nalchik.ru":true,"nnov.ru":true,"nov.ru":true,"novosibirsk.ru":true,"nsk.ru":true,"omsk.ru":true,"orenburg.ru":true,"oryol.ru":true,"palana.ru":true,"penza.ru":true,"perm.ru":true,"ptz.ru":true,"rnd.ru":true,"ryazan.ru":true,"sakhalin.ru":true,"samara.ru":true,"saratov.ru":true,"simbirsk.ru":true,"smolensk.ru":true,"spb.ru":true,"stavropol.ru":true,"stv.ru":true,"surgut.ru":true,"tambov.ru":true,"tatarstan.ru":true,"tom.ru":true,"tomsk.ru":true,"tsaritsyn.ru":true,"tsk.ru":true,"tula.ru":true,"tuva.ru":true,"tver.ru":true,"tyumen.ru":true,"udm.ru":true,"udmurtia.ru":true,"ulan-ude.ru":true,"vladikavkaz.ru":true,"vladimir.ru":true,"vladivostok.ru":true,"volgograd.ru":true,"vologda.ru":true,"voronezh.ru":true,"vrn.ru":true,"vyatka.ru":true,"yakutia.ru":true,"yamal.ru":true,"yaroslavl.ru":true,"yekaterinburg.ru":true,"yuzhno-sakhalinsk.ru":true,"amursk.ru":true,"baikal.ru":true,"cmw.ru":true,"fareast.ru":true,"jamal.ru":true,"kms.ru":true,"k-uralsk.ru":true,"kustanai.ru":true,"kuzbass.ru":true,"magnitka.ru":true,"mytis.ru":true,"nakhodka.ru":true,"nkz.ru":true,"norilsk.ru":true,"oskol.ru":true,"pyatigorsk.ru":true,"rubtsovsk.ru":true,"snz.ru":true,"syzran.ru":true,"vdonsk.ru":true,"zgrad.ru":true,"gov.ru":true,"mil.ru":true,"test.ru":true,"rw":true,"gov.rw":true,"net.rw":true,"edu.rw":true,"ac.rw":true,"com.rw":true,"co.rw":true,"int.rw":true,"mil.rw":true,"gouv.rw":true,"sa":true,"com.sa":true,"net.sa":true,"org.sa":true,"gov.sa":true,"med.sa":true,"pub.sa":true,"edu.sa":true,"sch.sa":true,"sb":true,"com.sb":true,"edu.sb":true,"gov.sb":true,"net.sb":true,"org.sb":true,"sc":true,"com.sc":true,"gov.sc":true,"net.sc":true,"org.sc":true,"edu.sc":true,"sd":true,"com.sd":true,"net.sd":true,"org.sd":true,"edu.sd":true,"med.sd":true,"tv.sd":true,"gov.sd":true,"info.sd":true,"se":true,"a.se":true,"ac.se":true,"b.se":true,"bd.se":true,"brand.se":true,"c.se":true,"d.se":true,"e.se":true,"f.se":true,"fh.se":true,"fhsk.se":true,"fhv.se":true,"g.se":true,"h.se":true,"i.se":true,"k.se":true,"komforb.se":true,"kommunalforbund.se":true,"komvux.se":true,"l.se":true,"lanbib.se":true,"m.se":true,"n.se":true,"naturbruksgymn.se":true,"o.se":true,"org.se":true,"p.se":true,"parti.se":true,"pp.se":true,"press.se":true,"r.se":true,"s.se":true,"t.se":true,"tm.se":true,"u.se":true,"w.se":true,"x.se":true,"y.se":true,"z.se":true,"sg":true,"com.sg":true,"net.sg":true,"org.sg":true,"gov.sg":true,"edu.sg":true,"per.sg":true,"sh":true,"com.sh":true,"net.sh":true,"gov.sh":true,"org.sh":true,"mil.sh":true,"si":true,"sj":true,"sk":true,"sl":true,"com.sl":true,"net.sl":true,"edu.sl":true,"gov.sl":true,"org.sl":true,"sm":true,"sn":true,"art.sn":true,"com.sn":true,"edu.sn":true,"gouv.sn":true,"org.sn":true,"perso.sn":true,"univ.sn":true,"so":true,"com.so":true,"net.so":true,"org.so":true,"sr":true,"st":true,"co.st":true,"com.st":true,"consulado.st":true,"edu.st":true,"embaixada.st":true,"gov.st":true,"mil.st":true,"net.st":true,"org.st":true,"principe.st":true,"saotome.st":true,"store.st":true,"su":true,"adygeya.su":true,"arkhangelsk.su":true,"balashov.su":true,"bashkiria.su":true,"bryansk.su":true,"dagestan.su":true,"grozny.su":true,"ivanovo.su":true,"kalmykia.su":true,"kaluga.su":true,"karelia.su":true,"khakassia.su":true,"krasnodar.su":true,"kurgan.su":true,"lenug.su":true,"mordovia.su":true,"msk.su":true,"murmansk.su":true,"nalchik.su":true,"nov.su":true,"obninsk.su":true,"penza.su":true,"pokrovsk.su":true,"sochi.su":true,"spb.su":true,"togliatti.su":true,"troitsk.su":true,"tula.su":true,"tuva.su":true,"vladikavkaz.su":true,"vladimir.su":true,"vologda.su":true,"sv":true,"com.sv":true,"edu.sv":true,"gob.sv":true,"org.sv":true,"red.sv":true,"sx":true,"gov.sx":true,"sy":true,"edu.sy":true,"gov.sy":true,"net.sy":true,"mil.sy":true,"com.sy":true,"org.sy":true,"sz":true,"co.sz":true,"ac.sz":true,"org.sz":true,"tc":true,"td":true,"tel":true,"tf":true,"tg":true,"th":true,"ac.th":true,"co.th":true,"go.th":true,"in.th":true,"mi.th":true,"net.th":true,"or.th":true,"tj":true,"ac.tj":true,"biz.tj":true,"co.tj":true,"com.tj":true,"edu.tj":true,"go.tj":true,"gov.tj":true,"int.tj":true,"mil.tj":true,"name.tj":true,"net.tj":true,"nic.tj":true,"org.tj":true,"test.tj":true,"web.tj":true,"tk":true,"tl":true,"gov.tl":true,"tm":true,"com.tm":true,"co.tm":true,"org.tm":true,"net.tm":true,"nom.tm":true,"gov.tm":true,"mil.tm":true,"edu.tm":true,"tn":true,"com.tn":true,"ens.tn":true,"fin.tn":true,"gov.tn":true,"ind.tn":true,"intl.tn":true,"nat.tn":true,"net.tn":true,"org.tn":true,"info.tn":true,"perso.tn":true,"tourism.tn":true,"edunet.tn":true,"rnrt.tn":true,"rns.tn":true,"rnu.tn":true,"mincom.tn":true,"agrinet.tn":true,"defense.tn":true,"turen.tn":true,"to":true,"com.to":true,"gov.to":true,"net.to":true,"org.to":true,"edu.to":true,"mil.to":true,"tp":true,"tr":true,"com.tr":true,"info.tr":true,"biz.tr":true,"net.tr":true,"org.tr":true,"web.tr":true,"gen.tr":true,"tv.tr":true,"av.tr":true,"dr.tr":true,"bbs.tr":true,"name.tr":true,"tel.tr":true,"gov.tr":true,"bel.tr":true,"pol.tr":true,"mil.tr":true,"k12.tr":true,"edu.tr":true,"kep.tr":true,"nc.tr":true,"gov.nc.tr":true,"travel":true,"tt":true,"co.tt":true,"com.tt":true,"org.tt":true,"net.tt":true,"biz.tt":true,"info.tt":true,"pro.tt":true,"int.tt":true,"coop.tt":true,"jobs.tt":true,"mobi.tt":true,"travel.tt":true,"museum.tt":true,"aero.tt":true,"name.tt":true,"gov.tt":true,"edu.tt":true,"tv":true,"tw":true,"edu.tw":true,"gov.tw":true,"mil.tw":true,"com.tw":true,"net.tw":true,"org.tw":true,"idv.tw":true,"game.tw":true,"ebiz.tw":true,"club.tw":true,"xn--zf0ao64a.tw":true,"xn--uc0atv.tw":true,"xn--czrw28b.tw":true,"tz":true,"ac.tz":true,"co.tz":true,"go.tz":true,"hotel.tz":true,"info.tz":true,"me.tz":true,"mil.tz":true,"mobi.tz":true,"ne.tz":true,"or.tz":true,"sc.tz":true,"tv.tz":true,"ua":true,"com.ua":true,"edu.ua":true,"gov.ua":true,"in.ua":true,"net.ua":true,"org.ua":true,"cherkassy.ua":true,"cherkasy.ua":true,"chernigov.ua":true,"chernihiv.ua":true,"chernivtsi.ua":true,"chernovtsy.ua":true,"ck.ua":true,"cn.ua":true,"cr.ua":true,"crimea.ua":true,"cv.ua":true,"dn.ua":true,"dnepropetrovsk.ua":true,"dnipropetrovsk.ua":true,"dominic.ua":true,"donetsk.ua":true,"dp.ua":true,"if.ua":true,"ivano-frankivsk.ua":true,"kh.ua":true,"kharkiv.ua":true,"kharkov.ua":true,"kherson.ua":true,"khmelnitskiy.ua":true,"khmelnytskyi.ua":true,"kiev.ua":true,"kirovograd.ua":true,"km.ua":true,"kr.ua":true,"krym.ua":true,"ks.ua":true,"kv.ua":true,"kyiv.ua":true,"lg.ua":true,"lt.ua":true,"lugansk.ua":true,"lutsk.ua":true,"lv.ua":true,"lviv.ua":true,"mk.ua":true,"mykolaiv.ua":true,"nikolaev.ua":true,"od.ua":true,"odesa.ua":true,"odessa.ua":true,"pl.ua":true,"poltava.ua":true,"rivne.ua":true,"rovno.ua":true,"rv.ua":true,"sb.ua":true,"sebastopol.ua":true,"sevastopol.ua":true,"sm.ua":true,"sumy.ua":true,"te.ua":true,"ternopil.ua":true,"uz.ua":true,"uzhgorod.ua":true,"vinnica.ua":true,"vinnytsia.ua":true,"vn.ua":true,"volyn.ua":true,"yalta.ua":true,"zaporizhzhe.ua":true,"zaporizhzhia.ua":true,"zhitomir.ua":true,"zhytomyr.ua":true,"zp.ua":true,"zt.ua":true,"ug":true,"co.ug":true,"or.ug":true,"ac.ug":true,"sc.ug":true,"go.ug":true,"ne.ug":true,"com.ug":true,"org.ug":true,"uk":true,"ac.uk":true,"co.uk":true,"gov.uk":true,"ltd.uk":true,"me.uk":true,"net.uk":true,"nhs.uk":true,"org.uk":true,"plc.uk":true,"police.uk":true,"*.sch.uk":true,"us":true,"dni.us":true,"fed.us":true,"isa.us":true,"kids.us":true,"nsn.us":true,"ak.us":true,"al.us":true,"ar.us":true,"as.us":true,"az.us":true,"ca.us":true,"co.us":true,"ct.us":true,"dc.us":true,"de.us":true,"fl.us":true,"ga.us":true,"gu.us":true,"hi.us":true,"ia.us":true,"id.us":true,"il.us":true,"in.us":true,"ks.us":true,"ky.us":true,"la.us":true,"ma.us":true,"md.us":true,"me.us":true,"mi.us":true,"mn.us":true,"mo.us":true,"ms.us":true,"mt.us":true,"nc.us":true,"nd.us":true,"ne.us":true,"nh.us":true,"nj.us":true,"nm.us":true,"nv.us":true,"ny.us":true,"oh.us":true,"ok.us":true,"or.us":true,"pa.us":true,"pr.us":true,"ri.us":true,"sc.us":true,"sd.us":true,"tn.us":true,"tx.us":true,"ut.us":true,"vi.us":true,"vt.us":true,"va.us":true,"wa.us":true,"wi.us":true,"wv.us":true,"wy.us":true,"k12.ak.us":true,"k12.al.us":true,"k12.ar.us":true,"k12.as.us":true,"k12.az.us":true,"k12.ca.us":true,"k12.co.us":true,"k12.ct.us":true,"k12.dc.us":true,"k12.de.us":true,"k12.fl.us":true,"k12.ga.us":true,"k12.gu.us":true,"k12.ia.us":true,"k12.id.us":true,"k12.il.us":true,"k12.in.us":true,"k12.ks.us":true,"k12.ky.us":true,"k12.la.us":true,"k12.ma.us":true,"k12.md.us":true,"k12.me.us":true,"k12.mi.us":true,"k12.mn.us":true,"k12.mo.us":true,"k12.ms.us":true,"k12.mt.us":true,"k12.nc.us":true,"k12.ne.us":true,"k12.nh.us":true,"k12.nj.us":true,"k12.nm.us":true,"k12.nv.us":true,"k12.ny.us":true,"k12.oh.us":true,"k12.ok.us":true,"k12.or.us":true,"k12.pa.us":true,"k12.pr.us":true,"k12.ri.us":true,"k12.sc.us":true,"k12.tn.us":true,"k12.tx.us":true,"k12.ut.us":true,"k12.vi.us":true,"k12.vt.us":true,"k12.va.us":true,"k12.wa.us":true,"k12.wi.us":true,"k12.wy.us":true,"cc.ak.us":true,"cc.al.us":true,"cc.ar.us":true,"cc.as.us":true,"cc.az.us":true,"cc.ca.us":true,"cc.co.us":true,"cc.ct.us":true,"cc.dc.us":true,"cc.de.us":true,"cc.fl.us":true,"cc.ga.us":true,"cc.gu.us":true,"cc.hi.us":true,"cc.ia.us":true,"cc.id.us":true,"cc.il.us":true,"cc.in.us":true,"cc.ks.us":true,"cc.ky.us":true,"cc.la.us":true,"cc.ma.us":true,"cc.md.us":true,"cc.me.us":true,"cc.mi.us":true,"cc.mn.us":true,"cc.mo.us":true,"cc.ms.us":true,"cc.mt.us":true,"cc.nc.us":true,"cc.nd.us":true,"cc.ne.us":true,"cc.nh.us":true,"cc.nj.us":true,"cc.nm.us":true,"cc.nv.us":true,"cc.ny.us":true,"cc.oh.us":true,"cc.ok.us":true,"cc.or.us":true,"cc.pa.us":true,"cc.pr.us":true,"cc.ri.us":true,"cc.sc.us":true,"cc.sd.us":true,"cc.tn.us":true,"cc.tx.us":true,"cc.ut.us":true,"cc.vi.us":true,"cc.vt.us":true,"cc.va.us":true,"cc.wa.us":true,"cc.wi.us":true,"cc.wv.us":true,"cc.wy.us":true,"lib.ak.us":true,"lib.al.us":true,"lib.ar.us":true,"lib.as.us":true,"lib.az.us":true,"lib.ca.us":true,"lib.co.us":true,"lib.ct.us":true,"lib.dc.us":true,"lib.de.us":true,"lib.fl.us":true,"lib.ga.us":true,"lib.gu.us":true,"lib.hi.us":true,"lib.ia.us":true,"lib.id.us":true,"lib.il.us":true,"lib.in.us":true,"lib.ks.us":true,"lib.ky.us":true,"lib.la.us":true,"lib.ma.us":true,"lib.md.us":true,"lib.me.us":true,"lib.mi.us":true,"lib.mn.us":true,"lib.mo.us":true,"lib.ms.us":true,"lib.mt.us":true,"lib.nc.us":true,"lib.nd.us":true,"lib.ne.us":true,"lib.nh.us":true,"lib.nj.us":true,"lib.nm.us":true,"lib.nv.us":true,"lib.ny.us":true,"lib.oh.us":true,"lib.ok.us":true,"lib.or.us":true,"lib.pa.us":true,"lib.pr.us":true,"lib.ri.us":true,"lib.sc.us":true,"lib.sd.us":true,"lib.tn.us":true,"lib.tx.us":true,"lib.ut.us":true,"lib.vi.us":true,"lib.vt.us":true,"lib.va.us":true,"lib.wa.us":true,"lib.wi.us":true,"lib.wy.us":true,"pvt.k12.ma.us":true,"chtr.k12.ma.us":true,"paroch.k12.ma.us":true,"uy":true,"com.uy":true,"edu.uy":true,"gub.uy":true,"mil.uy":true,"net.uy":true,"org.uy":true,"uz":true,"co.uz":true,"com.uz":true,"net.uz":true,"org.uz":true,"va":true,"vc":true,"com.vc":true,"net.vc":true,"org.vc":true,"gov.vc":true,"mil.vc":true,"edu.vc":true,"ve":true,"arts.ve":true,"co.ve":true,"com.ve":true,"e12.ve":true,"edu.ve":true,"firm.ve":true,"gob.ve":true,"gov.ve":true,"info.ve":true,"int.ve":true,"mil.ve":true,"net.ve":true,"org.ve":true,"rec.ve":true,"store.ve":true,"tec.ve":true,"web.ve":true,"vg":true,"vi":true,"co.vi":true,"com.vi":true,"k12.vi":true,"net.vi":true,"org.vi":true,"vn":true,"com.vn":true,"net.vn":true,"org.vn":true,"edu.vn":true,"gov.vn":true,"int.vn":true,"ac.vn":true,"biz.vn":true,"info.vn":true,"name.vn":true,"pro.vn":true,"health.vn":true,"vu":true,"com.vu":true,"edu.vu":true,"net.vu":true,"org.vu":true,"wf":true,"ws":true,"com.ws":true,"net.ws":true,"org.ws":true,"gov.ws":true,"edu.ws":true,"yt":true,"xn--mgbaam7a8h":true,"xn--y9a3aq":true,"xn--54b7fta0cc":true,"xn--90ais":true,"xn--fiqs8s":true,"xn--fiqz9s":true,"xn--lgbbat1ad8j":true,"xn--wgbh1c":true,"xn--node":true,"xn--qxam":true,"xn--j6w193g":true,"xn--h2brj9c":true,"xn--mgbbh1a71e":true,"xn--fpcrj9c3d":true,"xn--gecrj9c":true,"xn--s9brj9c":true,"xn--45brj9c":true,"xn--xkc2dl3a5ee0h":true,"xn--mgba3a4f16a":true,"xn--mgba3a4fra":true,"xn--mgbtx2b":true,"xn--mgbayh7gpa":true,"xn--3e0b707e":true,"xn--80ao21a":true,"xn--fzc2c9e2c":true,"xn--xkc2al3hye2a":true,"xn--mgbc0a9azcg":true,"xn--d1alf":true,"xn--l1acc":true,"xn--mix891f":true,"xn--mix082f":true,"xn--mgbx4cd0ab":true,"xn--mgb9awbf":true,"xn--mgbai9azgqp6j":true,"xn--mgbai9a5eva00b":true,"xn--ygbi2ammx":true,"xn--90a3ac":true,"xn--o1ac.xn--90a3ac":true,"xn--c1avg.xn--90a3ac":true,"xn--90azh.xn--90a3ac":true,"xn--d1at.xn--90a3ac":true,"xn--o1ach.xn--90a3ac":true,"xn--80au.xn--90a3ac":true,"xn--p1ai":true,"xn--wgbl6a":true,"xn--mgberp4a5d4ar":true,"xn--mgberp4a5d4a87g":true,"xn--mgbqly7c0a67fbc":true,"xn--mgbqly7cvafr":true,"xn--mgbpl2fh":true,"xn--yfro4i67o":true,"xn--clchc0ea0b2g2a9gcd":true,"xn--ogbpf8fl":true,"xn--mgbtf8fl":true,"xn--o3cw4h":true,"xn--pgbs0dh":true,"xn--kpry57d":true,"xn--kprw13d":true,"xn--nnx388a":true,"xn--j1amh":true,"xn--mgb2ddes":true,"xxx":true,"*.ye":true,"ac.za":true,"agrica.za":true,"alt.za":true,"co.za":true,"edu.za":true,"gov.za":true,"grondar.za":true,"law.za":true,"mil.za":true,"net.za":true,"ngo.za":true,"nis.za":true,"nom.za":true,"org.za":true,"school.za":true,"tm.za":true,"web.za":true,"*.zm":true,"*.zw":true,"aaa":true,"aarp":true,"abarth":true,"abb":true,"abbott":true,"abbvie":true,"abc":true,"able":true,"abogado":true,"abudhabi":true,"academy":true,"accenture":true,"accountant":true,"accountants":true,"aco":true,"active":true,"actor":true,"adac":true,"ads":true,"adult":true,"aeg":true,"aetna":true,"afamilycompany":true,"afl":true,"africa":true,"africamagic":true,"agakhan":true,"agency":true,"aig":true,"aigo":true,"airbus":true,"airforce":true,"airtel":true,"akdn":true,"alfaromeo":true,"alibaba":true,"alipay":true,"allfinanz":true,"allstate":true,"ally":true,"alsace":true,"alstom":true,"americanexpress":true,"americanfamily":true,"amex":true,"amfam":true,"amica":true,"amsterdam":true,"analytics":true,"android":true,"anquan":true,"anz":true,"aol":true,"apartments":true,"app":true,"apple":true,"aquarelle":true,"aramco":true,"archi":true,"army":true,"arte":true,"asda":true,"associates":true,"athleta":true,"attorney":true,"auction":true,"audi":true,"audible":true,"audio":true,"auspost":true,"author":true,"auto":true,"autos":true,"avianca":true,"aws":true,"axa":true,"azure":true,"baby":true,"baidu":true,"banamex":true,"bananarepublic":true,"band":true,"bank":true,"bar":true,"barcelona":true,"barclaycard":true,"barclays":true,"barefoot":true,"bargains":true,"basketball":true,"bauhaus":true,"bayern":true,"bbc":true,"bbt":true,"bbva":true,"bcg":true,"bcn":true,"beats":true,"beer":true,"bentley":true,"berlin":true,"best":true,"bestbuy":true,"bet":true,"bharti":true,"bible":true,"bid":true,"bike":true,"bing":true,"bingo":true,"bio":true,"black":true,"blackfriday":true,"blanco":true,"blockbuster":true,"blog":true,"bloomberg":true,"blue":true,"bms":true,"bmw":true,"bnl":true,"bnpparibas":true,"boats":true,"boehringer":true,"bofa":true,"bom":true,"bond":true,"boo":true,"book":true,"booking":true,"boots":true,"bosch":true,"bostik":true,"bot":true,"boutique":true,"bradesco":true,"bridgestone":true,"broadway":true,"broker":true,"brother":true,"brussels":true,"budapest":true,"bugatti":true,"build":true,"builders":true,"business":true,"buy":true,"buzz":true,"bzh":true,"cab":true,"cafe":true,"cal":true,"call":true,"calvinklein":true,"camera":true,"camp":true,"cancerresearch":true,"canon":true,"capetown":true,"capital":true,"capitalone":true,"car":true,"caravan":true,"cards":true,"care":true,"career":true,"careers":true,"cars":true,"cartier":true,"casa":true,"case":true,"caseih":true,"cash":true,"casino":true,"catering":true,"cba":true,"cbn":true,"cbre":true,"cbs":true,"ceb":true,"center":true,"ceo":true,"cern":true,"cfa":true,"cfd":true,"chanel":true,"channel":true,"chase":true,"chat":true,"cheap":true,"chintai":true,"chloe":true,"christmas":true,"chrome":true,"chrysler":true,"church":true,"cipriani":true,"circle":true,"cisco":true,"citadel":true,"citi":true,"citic":true,"city":true,"cityeats":true,"claims":true,"cleaning":true,"click":true,"clinic":true,"clothing":true,"cloud":true,"club":true,"clubmed":true,"coach":true,"codes":true,"coffee":true,"college":true,"cologne":true,"comcast":true,"commbank":true,"community":true,"company":true,"computer":true,"comsec":true,"condos":true,"construction":true,"consulting":true,"contact":true,"contractors":true,"cooking":true,"cookingchannel":true,"cool":true,"corsica":true,"country":true,"coupon":true,"coupons":true,"courses":true,"credit":true,"creditcard":true,"creditunion":true,"cricket":true,"crown":true,"crs":true,"cruises":true,"csc":true,"cuisinella":true,"cymru":true,"cyou":true,"dabur":true,"dad":true,"dance":true,"date":true,"dating":true,"datsun":true,"day":true,"dclk":true,"dds":true,"deal":true,"dealer":true,"deals":true,"degree":true,"delivery":true,"dell":true,"deloitte":true,"delta":true,"democrat":true,"dental":true,"dentist":true,"desi":true,"design":true,"dev":true,"dhl":true,"diamonds":true,"diet":true,"digital":true,"direct":true,"directory":true,"discount":true,"discover":true,"dish":true,"dnp":true,"docs":true,"dodge":true,"dog":true,"doha":true,"domains":true,"doosan":true,"dot":true,"download":true,"drive":true,"dstv":true,"dtv":true,"dubai":true,"duck":true,"dunlop":true,"duns":true,"dupont":true,"durban":true,"dvag":true,"dwg":true,"earth":true,"eat":true,"edeka":true,"education":true,"email":true,"emerck":true,"emerson":true,"energy":true,"engineer":true,"engineering":true,"enterprises":true,"epost":true,"epson":true,"equipment":true,"ericsson":true,"erni":true,"esq":true,"estate":true,"esurance":true,"etisalat":true,"eurovision":true,"eus":true,"events":true,"everbank":true,"exchange":true,"expert":true,"exposed":true,"express":true,"extraspace":true,"fage":true,"fail":true,"fairwinds":true,"faith":true,"family":true,"fan":true,"fans":true,"farm":true,"farmers":true,"fashion":true,"fast":true,"fedex":true,"feedback":true,"ferrari":true,"ferrero":true,"fiat":true,"fidelity":true,"fido":true,"film":true,"final":true,"finance":true,"financial":true,"fire":true,"firestone":true,"firmdale":true,"fish":true,"fishing":true,"fit":true,"fitness":true,"flickr":true,"flights":true,"flir":true,"florist":true,"flowers":true,"flsmidth":true,"fly":true,"foo":true,"foodnetwork":true,"football":true,"ford":true,"forex":true,"forsale":true,"forum":true,"foundation":true,"fox":true,"fresenius":true,"frl":true,"frogans":true,"frontdoor":true,"frontier":true,"ftr":true,"fujitsu":true,"fujixerox":true,"fund":true,"furniture":true,"futbol":true,"fyi":true,"gal":true,"gallery":true,"gallo":true,"gallup":true,"game":true,"games":true,"gap":true,"garden":true,"gbiz":true,"gdn":true,"gea":true,"gent":true,"genting":true,"george":true,"ggee":true,"gift":true,"gifts":true,"gives":true,"giving":true,"glade":true,"glass":true,"gle":true,"global":true,"globo":true,"gmail":true,"gmo":true,"gmx":true,"godaddy":true,"gold":true,"goldpoint":true,"golf":true,"goo":true,"goodhands":true,"goodyear":true,"goog":true,"google":true,"gop":true,"got":true,"gotv":true,"grainger":true,"graphics":true,"gratis":true,"green":true,"gripe":true,"group":true,"guardian":true,"gucci":true,"guge":true,"guide":true,"guitars":true,"guru":true,"hamburg":true,"hangout":true,"haus":true,"hbo":true,"hdfc":true,"hdfcbank":true,"health":true,"healthcare":true,"help":true,"helsinki":true,"here":true,"hermes":true,"hgtv":true,"hiphop":true,"hisamitsu":true,"hitachi":true,"hiv":true,"hkt":true,"hockey":true,"holdings":true,"holiday":true,"homedepot":true,"homegoods":true,"homes":true,"homesense":true,"honda":true,"honeywell":true,"horse":true,"host":true,"hosting":true,"hot":true,"hoteles":true,"hotmail":true,"house":true,"how":true,"hsbc":true,"htc":true,"hughes":true,"hyatt":true,"hyundai":true,"ibm":true,"icbc":true,"ice":true,"icu":true,"ieee":true,"ifm":true,"iinet":true,"ikano":true,"imamat":true,"imdb":true,"immo":true,"immobilien":true,"industries":true,"infiniti":true,"ing":true,"ink":true,"institute":true,"insurance":true,"insure":true,"intel":true,"international":true,"intuit":true,"investments":true,"ipiranga":true,"irish":true,"iselect":true,"ismaili":true,"ist":true,"istanbul":true,"itau":true,"itv":true,"iveco":true,"iwc":true,"jaguar":true,"java":true,"jcb":true,"jcp":true,"jeep":true,"jetzt":true,"jewelry":true,"jio":true,"jlc":true,"jll":true,"jmp":true,"jnj":true,"joburg":true,"jot":true,"joy":true,"jpmorgan":true,"jprs":true,"juegos":true,"juniper":true,"kaufen":true,"kddi":true,"kerryhotels":true,"kerrylogistics":true,"kerryproperties":true,"kfh":true,"kia":true,"kim":true,"kinder":true,"kindle":true,"kitchen":true,"kiwi":true,"koeln":true,"komatsu":true,"kosher":true,"kpmg":true,"kpn":true,"krd":true,"kred":true,"kuokgroup":true,"kyknet":true,"kyoto":true,"lacaixa":true,"ladbrokes":true,"lamborghini":true,"lancaster":true,"lancia":true,"lancome":true,"land":true,"landrover":true,"lanxess":true,"lasalle":true,"lat":true,"latino":true,"latrobe":true,"law":true,"lawyer":true,"lds":true,"lease":true,"leclerc":true,"lefrak":true,"legal":true,"lego":true,"lexus":true,"lgbt":true,"liaison":true,"lidl":true,"life":true,"lifeinsurance":true,"lifestyle":true,"lighting":true,"like":true,"lilly":true,"limited":true,"limo":true,"lincoln":true,"linde":true,"link":true,"lipsy":true,"live":true,"living":true,"lixil":true,"loan":true,"loans":true,"locker":true,"locus":true,"loft":true,"lol":true,"london":true,"lotte":true,"lotto":true,"love":true,"lpl":true,"lplfinancial":true,"ltd":true,"ltda":true,"lundbeck":true,"lupin":true,"luxe":true,"luxury":true,"macys":true,"madrid":true,"maif":true,"maison":true,"makeup":true,"man":true,"management":true,"mango":true,"market":true,"marketing":true,"markets":true,"marriott":true,"marshalls":true,"maserati":true,"mattel":true,"mba":true,"mcd":true,"mcdonalds":true,"mckinsey":true,"med":true,"media":true,"meet":true,"melbourne":true,"meme":true,"memorial":true,"men":true,"menu":true,"meo":true,"metlife":true,"miami":true,"microsoft":true,"mini":true,"mint":true,"mit":true,"mitsubishi":true,"mlb":true,"mls":true,"mma":true,"mnet":true,"mobily":true,"moda":true,"moe":true,"moi":true,"mom":true,"monash":true,"money":true,"monster":true,"montblanc":true,"mopar":true,"mormon":true,"mortgage":true,"moscow":true,"moto":true,"motorcycles":true,"mov":true,"movie":true,"movistar":true,"msd":true,"mtn":true,"mtpc":true,"mtr":true,"multichoice":true,"mutual":true,"mutuelle":true,"mzansimagic":true,"nab":true,"nadex":true,"nagoya":true,"naspers":true,"nationwide":true,"natura":true,"navy":true,"nba":true,"nec":true,"netbank":true,"netflix":true,"network":true,"neustar":true,"new":true,"newholland":true,"news":true,"next":true,"nextdirect":true,"nexus":true,"nfl":true,"ngo":true,"nhk":true,"nico":true,"nike":true,"nikon":true,"ninja":true,"nissan":true,"nokia":true,"northwesternmutual":true,"norton":true,"now":true,"nowruz":true,"nowtv":true,"nra":true,"nrw":true,"ntt":true,"nyc":true,"obi":true,"observer":true,"off":true,"office":true,"okinawa":true,"olayan":true,"olayangroup":true,"oldnavy":true,"ollo":true,"omega":true,"one":true,"ong":true,"onl":true,"online":true,"onyourside":true,"ooo":true,"open":true,"oracle":true,"orange":true,"organic":true,"orientexpress":true,"osaka":true,"otsuka":true,"ott":true,"ovh":true,"page":true,"pamperedchef":true,"panasonic":true,"panerai":true,"paris":true,"pars":true,"partners":true,"parts":true,"party":true,"passagens":true,"pay":true,"payu":true,"pccw":true,"pet":true,"pfizer":true,"pharmacy":true,"philips":true,"photo":true,"photography":true,"photos":true,"physio":true,"piaget":true,"pics":true,"pictet":true,"pictures":true,"pid":true,"pin":true,"ping":true,"pink":true,"pioneer":true,"pizza":true,"place":true,"play":true,"playstation":true,"plumbing":true,"plus":true,"pnc":true,"pohl":true,"poker":true,"politie":true,"porn":true,"pramerica":true,"praxi":true,"press":true,"prime":true,"prod":true,"productions":true,"prof":true,"progressive":true,"promo":true,"properties":true,"property":true,"protection":true,"pru":true,"prudential":true,"pub":true,"qpon":true,"quebec":true,"quest":true,"qvc":true,"racing":true,"raid":true,"read":true,"realestate":true,"realtor":true,"realty":true,"recipes":true,"red":true,"redstone":true,"redumbrella":true,"rehab":true,"reise":true,"reisen":true,"reit":true,"reliance":true,"ren":true,"rent":true,"rentals":true,"repair":true,"report":true,"republican":true,"rest":true,"restaurant":true,"review":true,"reviews":true,"rexroth":true,"rich":true,"richardli":true,"ricoh":true,"rightathome":true,"ril":true,"rio":true,"rip":true,"rocher":true,"rocks":true,"rodeo":true,"rogers":true,"room":true,"rsvp":true,"ruhr":true,"run":true,"rwe":true,"ryukyu":true,"saarland":true,"safe":true,"safety":true,"sakura":true,"sale":true,"salon":true,"samsclub":true,"samsung":true,"sandvik":true,"sandvikcoromant":true,"sanofi":true,"sap":true,"sapo":true,"sarl":true,"sas":true,"save":true,"saxo":true,"sbi":true,"sbs":true,"sca":true,"scb":true,"schaeffler":true,"schmidt":true,"scholarships":true,"school":true,"schule":true,"schwarz":true,"science":true,"scjohnson":true,"scor":true,"scot":true,"seat":true,"secure":true,"security":true,"seek":true,"sener":true,"services":true,"ses":true,"seven":true,"sew":true,"sex":true,"sexy":true,"sfr":true,"shangrila":true,"sharp":true,"shaw":true,"shell":true,"shia":true,"shiksha":true,"shoes":true,"shouji":true,"show":true,"showtime":true,"shriram":true,"silk":true,"sina":true,"singles":true,"site":true,"ski":true,"skin":true,"sky":true,"skype":true,"sling":true,"smart":true,"smile":true,"sncf":true,"soccer":true,"social":true,"softbank":true,"software":true,"sohu":true,"solar":true,"solutions":true,"song":true,"sony":true,"soy":true,"space":true,"spiegel":true,"spot":true,"spreadbetting":true,"srl":true,"srt":true,"stada":true,"staples":true,"star":true,"starhub":true,"statebank":true,"statefarm":true,"statoil":true,"stc":true,"stcgroup":true,"stockholm":true,"storage":true,"store":true,"studio":true,"study":true,"style":true,"sucks":true,"supersport":true,"supplies":true,"supply":true,"support":true,"surf":true,"surgery":true,"suzuki":true,"swatch":true,"swiftcover":true,"swiss":true,"sydney":true,"symantec":true,"systems":true,"tab":true,"taipei":true,"talk":true,"taobao":true,"target":true,"tatamotors":true,"tatar":true,"tattoo":true,"tax":true,"taxi":true,"tci":true,"tdk":true,"team":true,"tech":true,"technology":true,"telecity":true,"telefonica":true,"temasek":true,"tennis":true,"teva":true,"thd":true,"theater":true,"theatre":true,"theguardian":true,"tiaa":true,"tickets":true,"tienda":true,"tiffany":true,"tips":true,"tires":true,"tirol":true,"tjmaxx":true,"tjx":true,"tkmaxx":true,"tmall":true,"today":true,"tokyo":true,"tools":true,"top":true,"toray":true,"toshiba":true,"total":true,"tours":true,"town":true,"toyota":true,"toys":true,"trade":true,"trading":true,"training":true,"travelchannel":true,"travelers":true,"travelersinsurance":true,"trust":true,"trv":true,"tube":true,"tui":true,"tunes":true,"tushu":true,"tvs":true,"ubank":true,"ubs":true,"uconnect":true,"university":true,"uno":true,"uol":true,"ups":true,"vacations":true,"vana":true,"vanguard":true,"vegas":true,"ventures":true,"verisign":true,"versicherung":true,"vet":true,"viajes":true,"video":true,"vig":true,"viking":true,"villas":true,"vin":true,"vip":true,"virgin":true,"visa":true,"vision":true,"vista":true,"vistaprint":true,"viva":true,"vivo":true,"vlaanderen":true,"vodka":true,"volkswagen":true,"vote":true,"voting":true,"voto":true,"voyage":true,"vuelos":true,"wales":true,"walmart":true,"walter":true,"wang":true,"wanggou":true,"warman":true,"watch":true,"watches":true,"weather":true,"weatherchannel":true,"webcam":true,"weber":true,"website":true,"wed":true,"wedding":true,"weibo":true,"weir":true,"whoswho":true,"wien":true,"wiki":true,"williamhill":true,"win":true,"windows":true,"wine":true,"winners":true,"wme":true,"wolterskluwer":true,"woodside":true,"work":true,"works":true,"world":true,"wtc":true,"wtf":true,"xbox":true,"xerox":true,"xfinity":true,"xihuan":true,"xin":true,"xn--11b4c3d":true,"xn--1ck2e1b":true,"xn--1qqw23a":true,"xn--30rr7y":true,"xn--3bst00m":true,"xn--3ds443g":true,"xn--3oq18vl8pn36a":true,"xn--3pxu8k":true,"xn--42c2d9a":true,"xn--45q11c":true,"xn--4gbrim":true,"xn--4gq48lf9j":true,"xn--55qw42g":true,"xn--55qx5d":true,"xn--5su34j936bgsg":true,"xn--5tzm5g":true,"xn--6frz82g":true,"xn--6qq986b3xl":true,"xn--80adxhks":true,"xn--80asehdb":true,"xn--80aswg":true,"xn--8y0a063a":true,"xn--9dbq2a":true,"xn--9et52u":true,"xn--9krt00a":true,"xn--b4w605ferd":true,"xn--bck1b9a5dre4c":true,"xn--c1avg":true,"xn--c2br7g":true,"xn--cck2b3b":true,"xn--cg4bki":true,"xn--czr694b":true,"xn--czrs0t":true,"xn--czru2d":true,"xn--d1acj3b":true,"xn--eckvdtc9d":true,"xn--efvy88h":true,"xn--estv75g":true,"xn--fct429k":true,"xn--fhbei":true,"xn--fiq228c5hs":true,"xn--fiq64b":true,"xn--fjq720a":true,"xn--flw351e":true,"xn--fzys8d69uvgm":true,"xn--g2xx48c":true,"xn--gckr3f0f":true,"xn--hxt814e":true,"xn--i1b6b1a6a2e":true,"xn--imr513n":true,"xn--io0a7i":true,"xn--j1aef":true,"xn--jlq61u9w7b":true,"xn--jvr189m":true,"xn--kcrx77d1x4a":true,"xn--kpu716f":true,"xn--kput3i":true,"xn--mgba3a3ejt":true,"xn--mgba7c0bbn0a":true,"xn--mgbaakc7dvf":true,"xn--mgbab2bd":true,"xn--mgbb9fbpob":true,"xn--mgbca7dzdo":true,"xn--mgbt3dhd":true,"xn--mk1bu44c":true,"xn--mxtq1m":true,"xn--ngbc5azd":true,"xn--ngbe9e0a":true,"xn--nqv7f":true,"xn--nqv7fs00ema":true,"xn--nyqy26a":true,"xn--p1acf":true,"xn--pbt977c":true,"xn--pssy2u":true,"xn--q9jyb4c":true,"xn--qcka1pmc":true,"xn--rhqv96g":true,"xn--rovu88b":true,"xn--ses554g":true,"xn--t60b56a":true,"xn--tckwe":true,"xn--unup4y":true,"xn--vermgensberater-ctb":true,"xn--vermgensberatung-pwb":true,"xn--vhquv":true,"xn--vuq861b":true,"xn--w4r85el8fhu5dnra":true,"xn--w4rs40l":true,"xn--xhq521b":true,"xn--zfr164b":true,"xperia":true,"xyz":true,"yachts":true,"yahoo":true,"yamaxun":true,"yandex":true,"yodobashi":true,"yoga":true,"yokohama":true,"you":true,"youtube":true,"yun":true,"zappos":true,"zara":true,"zero":true,"zip":true,"zippo":true,"zone":true,"zuerich":true,"cloudfront.net":true,"ap-northeast-1.compute.amazonaws.com":true,"ap-southeast-1.compute.amazonaws.com":true,"ap-southeast-2.compute.amazonaws.com":true,"cn-north-1.compute.amazonaws.cn":true,"compute.amazonaws.cn":true,"compute.amazonaws.com":true,"compute-1.amazonaws.com":true,"eu-west-1.compute.amazonaws.com":true,"eu-central-1.compute.amazonaws.com":true,"sa-east-1.compute.amazonaws.com":true,"us-east-1.amazonaws.com":true,"us-gov-west-1.compute.amazonaws.com":true,"us-west-1.compute.amazonaws.com":true,"us-west-2.compute.amazonaws.com":true,"z-1.compute-1.amazonaws.com":true,"z-2.compute-1.amazonaws.com":true,"elasticbeanstalk.com":true,"elb.amazonaws.com":true,"s3.amazonaws.com":true,"s3-ap-northeast-1.amazonaws.com":true,"s3-ap-southeast-1.amazonaws.com":true,"s3-ap-southeast-2.amazonaws.com":true,"s3-external-1.amazonaws.com":true,"s3-external-2.amazonaws.com":true,"s3-fips-us-gov-west-1.amazonaws.com":true,"s3-eu-central-1.amazonaws.com":true,"s3-eu-west-1.amazonaws.com":true,"s3-sa-east-1.amazonaws.com":true,"s3-us-gov-west-1.amazonaws.com":true,"s3-us-west-1.amazonaws.com":true,"s3-us-west-2.amazonaws.com":true,"s3.cn-north-1.amazonaws.com.cn":true,"s3.eu-central-1.amazonaws.com":true,"betainabox.com":true,"ae.org":true,"ar.com":true,"br.com":true,"cn.com":true,"com.de":true,"com.se":true,"de.com":true,"eu.com":true,"gb.com":true,"gb.net":true,"hu.com":true,"hu.net":true,"jp.net":true,"jpn.com":true,"kr.com":true,"mex.com":true,"no.com":true,"qc.com":true,"ru.com":true,"sa.com":true,"se.com":true,"se.net":true,"uk.com":true,"uk.net":true,"us.com":true,"uy.com":true,"za.bz":true,"za.com":true,"africa.com":true,"gr.com":true,"in.net":true,"us.org":true,"co.com":true,"c.la":true,"cloudcontrolled.com":true,"cloudcontrolapp.com":true,"co.ca":true,"c.cdn77.org":true,"cdn77-ssl.net":true,"r.cdn77.net":true,"rsc.cdn77.org":true,"ssl.origin.cdn77-secure.org":true,"co.nl":true,"co.no":true,"*.platform.sh":true,"cupcake.is":true,"dreamhosters.com":true,"duckdns.org":true,"dyndns-at-home.com":true,"dyndns-at-work.com":true,"dyndns-blog.com":true,"dyndns-free.com":true,"dyndns-home.com":true,"dyndns-ip.com":true,"dyndns-mail.com":true,"dyndns-office.com":true,"dyndns-pics.com":true,"dyndns-remote.com":true,"dyndns-server.com":true,"dyndns-web.com":true,"dyndns-wiki.com":true,"dyndns-work.com":true,"dyndns.biz":true,"dyndns.info":true,"dyndns.org":true,"dyndns.tv":true,"at-band-camp.net":true,"ath.cx":true,"barrel-of-knowledge.info":true,"barrell-of-knowledge.info":true,"better-than.tv":true,"blogdns.com":true,"blogdns.net":true,"blogdns.org":true,"blogsite.org":true,"boldlygoingnowhere.org":true,"broke-it.net":true,"buyshouses.net":true,"cechire.com":true,"dnsalias.com":true,"dnsalias.net":true,"dnsalias.org":true,"dnsdojo.com":true,"dnsdojo.net":true,"dnsdojo.org":true,"does-it.net":true,"doesntexist.com":true,"doesntexist.org":true,"dontexist.com":true,"dontexist.net":true,"dontexist.org":true,"doomdns.com":true,"doomdns.org":true,"dvrdns.org":true,"dyn-o-saur.com":true,"dynalias.com":true,"dynalias.net":true,"dynalias.org":true,"dynathome.net":true,"dyndns.ws":true,"endofinternet.net":true,"endofinternet.org":true,"endoftheinternet.org":true,"est-a-la-maison.com":true,"est-a-la-masion.com":true,"est-le-patron.com":true,"est-mon-blogueur.com":true,"for-better.biz":true,"for-more.biz":true,"for-our.info":true,"for-some.biz":true,"for-the.biz":true,"forgot.her.name":true,"forgot.his.name":true,"from-ak.com":true,"from-al.com":true,"from-ar.com":true,"from-az.net":true,"from-ca.com":true,"from-co.net":true,"from-ct.com":true,"from-dc.com":true,"from-de.com":true,"from-fl.com":true,"from-ga.com":true,"from-hi.com":true,"from-ia.com":true,"from-id.com":true,"from-il.com":true,"from-in.com":true,"from-ks.com":true,"from-ky.com":true,"from-la.net":true,"from-ma.com":true,"from-md.com":true,"from-me.org":true,"from-mi.com":true,"from-mn.com":true,"from-mo.com":true,"from-ms.com":true,"from-mt.com":true,"from-nc.com":true,"from-nd.com":true,"from-ne.com":true,"from-nh.com":true,"from-nj.com":true,"from-nm.com":true,"from-nv.com":true,"from-ny.net":true,"from-oh.com":true,"from-ok.com":true,"from-or.com":true,"from-pa.com":true,"from-pr.com":true,"from-ri.com":true,"from-sc.com":true,"from-sd.com":true,"from-tn.com":true,"from-tx.com":true,"from-ut.com":true,"from-va.com":true,"from-vt.com":true,"from-wa.com":true,"from-wi.com":true,"from-wv.com":true,"from-wy.com":true,"ftpaccess.cc":true,"fuettertdasnetz.de":true,"game-host.org":true,"game-server.cc":true,"getmyip.com":true,"gets-it.net":true,"go.dyndns.org":true,"gotdns.com":true,"gotdns.org":true,"groks-the.info":true,"groks-this.info":true,"ham-radio-op.net":true,"here-for-more.info":true,"hobby-site.com":true,"hobby-site.org":true,"home.dyndns.org":true,"homedns.org":true,"homeftp.net":true,"homeftp.org":true,"homeip.net":true,"homelinux.com":true,"homelinux.net":true,"homelinux.org":true,"homeunix.com":true,"homeunix.net":true,"homeunix.org":true,"iamallama.com":true,"in-the-band.net":true,"is-a-anarchist.com":true,"is-a-blogger.com":true,"is-a-bookkeeper.com":true,"is-a-bruinsfan.org":true,"is-a-bulls-fan.com":true,"is-a-candidate.org":true,"is-a-caterer.com":true,"is-a-celticsfan.org":true,"is-a-chef.com":true,"is-a-chef.net":true,"is-a-chef.org":true,"is-a-conservative.com":true,"is-a-cpa.com":true,"is-a-cubicle-slave.com":true,"is-a-democrat.com":true,"is-a-designer.com":true,"is-a-doctor.com":true,"is-a-financialadvisor.com":true,"is-a-geek.com":true,"is-a-geek.net":true,"is-a-geek.org":true,"is-a-green.com":true,"is-a-guru.com":true,"is-a-hard-worker.com":true,"is-a-hunter.com":true,"is-a-knight.org":true,"is-a-landscaper.com":true,"is-a-lawyer.com":true,"is-a-liberal.com":true,"is-a-libertarian.com":true,"is-a-linux-user.org":true,"is-a-llama.com":true,"is-a-musician.com":true,"is-a-nascarfan.com":true,"is-a-nurse.com":true,"is-a-painter.com":true,"is-a-patsfan.org":true,"is-a-personaltrainer.com":true,"is-a-photographer.com":true,"is-a-player.com":true,"is-a-republican.com":true,"is-a-rockstar.com":true,"is-a-socialist.com":true,"is-a-soxfan.org":true,"is-a-student.com":true,"is-a-teacher.com":true,"is-a-techie.com":true,"is-a-therapist.com":true,"is-an-accountant.com":true,"is-an-actor.com":true,"is-an-actress.com":true,"is-an-anarchist.com":true,"is-an-artist.com":true,"is-an-engineer.com":true,"is-an-entertainer.com":true,"is-by.us":true,"is-certified.com":true,"is-found.org":true,"is-gone.com":true,"is-into-anime.com":true,"is-into-cars.com":true,"is-into-cartoons.com":true,"is-into-games.com":true,"is-leet.com":true,"is-lost.org":true,"is-not-certified.com":true,"is-saved.org":true,"is-slick.com":true,"is-uberleet.com":true,"is-very-bad.org":true,"is-very-evil.org":true,"is-very-good.org":true,"is-very-nice.org":true,"is-very-sweet.org":true,"is-with-theband.com":true,"isa-geek.com":true,"isa-geek.net":true,"isa-geek.org":true,"isa-hockeynut.com":true,"issmarterthanyou.com":true,"isteingeek.de":true,"istmein.de":true,"kicks-ass.net":true,"kicks-ass.org":true,"knowsitall.info":true,"land-4-sale.us":true,"lebtimnetz.de":true,"leitungsen.de":true,"likes-pie.com":true,"likescandy.com":true,"merseine.nu":true,"mine.nu":true,"misconfused.org":true,"mypets.ws":true,"myphotos.cc":true,"neat-url.com":true,"office-on-the.net":true,"on-the-web.tv":true,"podzone.net":true,"podzone.org":true,"readmyblog.org":true,"saves-the-whales.com":true,"scrapper-site.net":true,"scrapping.cc":true,"selfip.biz":true,"selfip.com":true,"selfip.info":true,"selfip.net":true,"selfip.org":true,"sells-for-less.com":true,"sells-for-u.com":true,"sells-it.net":true,"sellsyourhome.org":true,"servebbs.com":true,"servebbs.net":true,"servebbs.org":true,"serveftp.net":true,"serveftp.org":true,"servegame.org":true,"shacknet.nu":true,"simple-url.com":true,"space-to-rent.com":true,"stuff-4-sale.org":true,"stuff-4-sale.us":true,"teaches-yoga.com":true,"thruhere.net":true,"traeumtgerade.de":true,"webhop.biz":true,"webhop.info":true,"webhop.net":true,"webhop.org":true,"worse-than.tv":true,"writesthisblog.com":true,"eu.org":true,"al.eu.org":true,"asso.eu.org":true,"at.eu.org":true,"au.eu.org":true,"be.eu.org":true,"bg.eu.org":true,"ca.eu.org":true,"cd.eu.org":true,"ch.eu.org":true,"cn.eu.org":true,"cy.eu.org":true,"cz.eu.org":true,"de.eu.org":true,"dk.eu.org":true,"edu.eu.org":true,"ee.eu.org":true,"es.eu.org":true,"fi.eu.org":true,"fr.eu.org":true,"gr.eu.org":true,"hr.eu.org":true,"hu.eu.org":true,"ie.eu.org":true,"il.eu.org":true,"in.eu.org":true,"int.eu.org":true,"is.eu.org":true,"it.eu.org":true,"jp.eu.org":true,"kr.eu.org":true,"lt.eu.org":true,"lu.eu.org":true,"lv.eu.org":true,"mc.eu.org":true,"me.eu.org":true,"mk.eu.org":true,"mt.eu.org":true,"my.eu.org":true,"net.eu.org":true,"ng.eu.org":true,"nl.eu.org":true,"no.eu.org":true,"nz.eu.org":true,"paris.eu.org":true,"pl.eu.org":true,"pt.eu.org":true,"q-a.eu.org":true,"ro.eu.org":true,"ru.eu.org":true,"se.eu.org":true,"si.eu.org":true,"sk.eu.org":true,"tr.eu.org":true,"uk.eu.org":true,"us.eu.org":true,"a.ssl.fastly.net":true,"b.ssl.fastly.net":true,"global.ssl.fastly.net":true,"a.prod.fastly.net":true,"global.prod.fastly.net":true,"firebaseapp.com":true,"flynnhub.com":true,"service.gov.uk":true,"github.io":true,"githubusercontent.com":true,"ro.com":true,"appspot.com":true,"blogspot.ae":true,"blogspot.al":true,"blogspot.am":true,"blogspot.ba":true,"blogspot.be":true,"blogspot.bg":true,"blogspot.bj":true,"blogspot.ca":true,"blogspot.cf":true,"blogspot.ch":true,"blogspot.cl":true,"blogspot.co.at":true,"blogspot.co.id":true,"blogspot.co.il":true,"blogspot.co.ke":true,"blogspot.co.nz":true,"blogspot.co.uk":true,"blogspot.co.za":true,"blogspot.com":true,"blogspot.com.ar":true,"blogspot.com.au":true,"blogspot.com.br":true,"blogspot.com.by":true,"blogspot.com.co":true,"blogspot.com.cy":true,"blogspot.com.ee":true,"blogspot.com.eg":true,"blogspot.com.es":true,"blogspot.com.mt":true,"blogspot.com.ng":true,"blogspot.com.tr":true,"blogspot.com.uy":true,"blogspot.cv":true,"blogspot.cz":true,"blogspot.de":true,"blogspot.dk":true,"blogspot.fi":true,"blogspot.fr":true,"blogspot.gr":true,"blogspot.hk":true,"blogspot.hr":true,"blogspot.hu":true,"blogspot.ie":true,"blogspot.in":true,"blogspot.is":true,"blogspot.it":true,"blogspot.jp":true,"blogspot.kr":true,"blogspot.li":true,"blogspot.lt":true,"blogspot.lu":true,"blogspot.md":true,"blogspot.mk":true,"blogspot.mr":true,"blogspot.mx":true,"blogspot.my":true,"blogspot.nl":true,"blogspot.no":true,"blogspot.pe":true,"blogspot.pt":true,"blogspot.qa":true,"blogspot.re":true,"blogspot.ro":true,"blogspot.rs":true,"blogspot.ru":true,"blogspot.se":true,"blogspot.sg":true,"blogspot.si":true,"blogspot.sk":true,"blogspot.sn":true,"blogspot.td":true,"blogspot.tw":true,"blogspot.ug":true,"blogspot.vn":true,"codespot.com":true,"googleapis.com":true,"googlecode.com":true,"pagespeedmobilizer.com":true,"withgoogle.com":true,"withyoutube.com":true,"herokuapp.com":true,"herokussl.com":true,"iki.fi":true,"biz.at":true,"info.at":true,"co.pl":true,"azurewebsites.net":true,"azure-mobile.net":true,"cloudapp.net":true,"bmoattachments.org":true,"4u.com":true,"nfshost.com":true,"nyc.mn":true,"nid.io":true,"operaunite.com":true,"outsystemscloud.com":true,"art.pl":true,"gliwice.pl":true,"krakow.pl":true,"poznan.pl":true,"wroc.pl":true,"zakopane.pl":true,"pantheon.io":true,"gotpantheon.com":true,"priv.at":true,"qa2.com":true,"rhcloud.com":true,"sandcats.io":true,"biz.ua":true,"co.ua":true,"pp.ua":true,"sinaapp.com":true,"vipsinaapp.com":true,"1kapp.com":true,"gda.pl":true,"gdansk.pl":true,"gdynia.pl":true,"med.pl":true,"sopot.pl":true,"hk.com":true,"hk.org":true,"ltd.hk":true,"inc.hk":true,"yolasite.com":true,"za.net":true,"za.org":true});
 
// END of automatically generated file
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/store.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tough-cookie/lib/store.js

Statements: 58.82% (10 / 17)      Branches: 100% (0 / 0)      Functions: 12.5% (1 / 8)      Lines: 58.82% (10 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                                                  1   1         1   1       1       1       1           1       1       1        
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';
/*jshint unused:false */
 
function Store() {
}
exports.Store = Store;
 
// Stores may be synchronous, but are still required to use a
// Continuation-Passing Style API.  The CookieJar itself will expose a "*Sync"
// API that converts from synchronous-callbacks to imperative style.
Store.prototype.synchronous = false;
 
Store.prototype.findCookie = function(domain, path, key, cb) {
  throw new Error('findCookie is not implemented');
};
 
Store.prototype.findCookies = function(domain, path, cb) {
  throw new Error('findCookies is not implemented');
};
 
Store.prototype.putCookie = function(cookie, cb) {
  throw new Error('putCookie is not implemented');
};
 
Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
  // recommended default implementation:
  // return this.putCookie(newCookie, cb);
  throw new Error('updateCookie is not implemented');
};
 
Store.prototype.removeCookie = function(domain, path, key, cb) {
  throw new Error('removeCookie is not implemented');
};
 
Store.prototype.removeCookies = function(domain, path, cb) {
  throw new Error('removeCookies is not implemented');
};
 
Store.prototype.getAllCookies = function(cb) {
  throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tunnel-agent/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tunnel-agent/

Statements: 19.42% (27 / 139)      Branches: 5.88% (2 / 34)      Functions: 0% (0 / 23)      Lines: 19.57% (27 / 138)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tunnel-agent/
File Statements Branches Functions Lines
index.js 19.42% (27 / 139) 5.88% (2 / 34) 0% (0 / 23) 19.57% (27 / 138)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tunnel-agent/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/request/node_modules/tunnel-agent/index.js

Statements: 19.42% (27 / 139)      Branches: 5.88% (2 / 34)      Functions: 0% (0 / 23)      Lines: 19.57% (27 / 138)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246    1                   1 1 1 1     1           1               1           1                 1                                             1   1                                           1                 1       1                 1                                                   1         1             1                                   1                     1                           1                             1                                 1 1                     1   1    
'use strict'
 
var net = require('net')
  , tls = require('tls')
  , http = require('http')
  , https = require('https')
  , events = require('events')
  , assert = require('assert')
  , util = require('util')
  , Buffer = require('safe-buffer').Buffer
  ;
 
exports.httpOverHttp = httpOverHttp
exports.httpsOverHttp = httpsOverHttp
exports.httpOverHttps = httpOverHttps
exports.httpsOverHttps = httpsOverHttps
 
 
function httpOverHttp(options) {
  var agent = new TunnelingAgent(options)
  agent.request = http.request
  return agent
}
 
function httpsOverHttp(options) {
  var agent = new TunnelingAgent(options)
  agent.request = http.request
  agent.createSocket = createSecureSocket
  agent.defaultPort = 443
  return agent
}
 
function httpOverHttps(options) {
  var agent = new TunnelingAgent(options)
  agent.request = https.request
  return agent
}
 
function httpsOverHttps(options) {
  var agent = new TunnelingAgent(options)
  agent.request = https.request
  agent.createSocket = createSecureSocket
  agent.defaultPort = 443
  return agent
}
 
 
function TunnelingAgent(options) {
  var self = this
  self.options = options || {}
  self.proxyOptions = self.options.proxy || {}
  self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets
  self.requests = []
  self.sockets = []
 
  self.on('free', function onFree(socket, host, port) {
    for (var i = 0, len = self.requests.length; i < len; ++i) {
      var pending = self.requests[i]
      if (pending.host === host && pending.port === port) {
        // Detect the request to connect same origin server,
        // reuse the connection.
        self.requests.splice(i, 1)
        pending.request.onSocket(socket)
        return
      }
    }
    socket.destroy()
    self.removeSocket(socket)
  })
}
util.inherits(TunnelingAgent, events.EventEmitter)
 
TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
  var self = this
 
   // Legacy API: addRequest(req, host, port, path)
  if (typeof options === 'string') {
    options = {
      host: options,
      port: arguments[2],
      path: arguments[3]
    };
  }
 
  if (self.sockets.length >= this.maxSockets) {
    // We are over limit so we'll add it to the queue.
    self.requests.push({host: options.host, port: options.port, request: req})
    return
  }
 
  // If we are under maxSockets create a new one.
  self.createConnection({host: options.host, port: options.port, request: req})
}
 
TunnelingAgent.prototype.createConnection = function createConnection(pending) {
  var self = this
 
  self.createSocket(pending, function(socket) {
    socket.on('free', onFree)
    socket.on('close', onCloseOrRemove)
    socket.on('agentRemove', onCloseOrRemove)
    pending.request.onSocket(socket)
 
    function onFree() {
      self.emit('free', socket, pending.host, pending.port)
    }
 
    function onCloseOrRemove(err) {
      self.removeSocket(socket)
      socket.removeListener('free', onFree)
      socket.removeListener('close', onCloseOrRemove)
      socket.removeListener('agentRemove', onCloseOrRemove)
    }
  })
}
 
TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
  var self = this
  var placeholder = {}
  self.sockets.push(placeholder)
 
  var connectOptions = mergeOptions({}, self.proxyOptions,
    { method: 'CONNECT'
    , path: options.host + ':' + options.port
    , agent: false
    }
  )
  if (connectOptions.proxyAuth) {
    connectOptions.headers = connectOptions.headers || {}
    connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
        Buffer.from(connectOptions.proxyAuth).toString('base64')
  }
 
  debug('making CONNECT request')
  var connectReq = self.request(connectOptions)
  connectReq.useChunkedEncodingByDefault = false // for v0.6
  connectReq.once('response', onResponse) // for v0.6
  connectReq.once('upgrade', onUpgrade)   // for v0.6
  connectReq.once('connect', onConnect)   // for v0.7 or later
  connectReq.once('error', onError)
  connectReq.end()
 
  function onResponse(res) {
    // Very hacky. This is necessary to avoid http-parser leaks.
    res.upgrade = true
  }
 
  function onUpgrade(res, socket, head) {
    // Hacky.
    process.nextTick(function() {
      onConnect(res, socket, head)
    })
  }
 
  function onConnect(res, socket, head) {
    connectReq.removeAllListeners()
    socket.removeAllListeners()
 
    if (res.statusCode === 200) {
      assert.equal(head.length, 0)
      debug('tunneling connection has established')
      self.sockets[self.sockets.indexOf(placeholder)] = socket
      cb(socket)
    } else {
      debug('tunneling socket could not be established, statusCode=%d', res.statusCode)
      var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)
      error.code = 'ECONNRESET'
      options.request.emit('error', error)
      self.removeSocket(placeholder)
    }
  }
 
  function onError(cause) {
    connectReq.removeAllListeners()
 
    debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack)
    var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)
    error.code = 'ECONNRESET'
    options.request.emit('error', error)
    self.removeSocket(placeholder)
  }
}
 
TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
  var pos = this.sockets.indexOf(socket)
  if (pos === -1) return
 
  this.sockets.splice(pos, 1)
 
  var pending = this.requests.shift()
  if (pending) {
    // If we have pending requests and a socket gets closed a new one
    // needs to be created to take over in the pool for the one that closed.
    this.createConnection(pending)
  }
}
 
function createSecureSocket(options, cb) {
  var self = this
  TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
    // 0 is dummy port for v0.6
    var secureSocket = tls.connect(0, mergeOptions({}, self.options,
      { servername: options.host
      , socket: socket
      }
    ))
    self.sockets[self.sockets.indexOf(socket)] = secureSocket
    cb(secureSocket)
  })
}
 
 
function mergeOptions(target) {
  for (var i = 1, len = arguments.length; i < len; ++i) {
    var overrides = arguments[i]
    if (typeof overrides === 'object') {
      var keys = Object.keys(overrides)
      for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
        var k = keys[j]
        if (overrides[k] !== undefined) {
          target[k] = overrides[k]
        }
      }
    }
  }
  return target
}
 
 
var debug
Iif (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
  debug = function() {
    var args = Array.prototype.slice.call(arguments)
    if (typeof args[0] === 'string') {
      args[0] = 'TUNNEL: ' + args[0]
    } else {
      args.unshift('TUNNEL:')
    }
    console.error.apply(console, args)
  }
} else {
  debug = function() {}
}
exports.debug = debug // for test
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/retry/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
module.exports = require('./lib/retry');
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/lib/

Statements: 12.12% (16 / 132)      Branches: 0% (0 / 61)      Functions: 0% (0 / 20)      Lines: 12.12% (16 / 132)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/retry/lib/
File Statements Branches Functions Lines
retry.js 10% (5 / 50) 0% (0 / 25) 0% (0 / 8) 10% (5 / 50)
retry_operation.js 13.41% (11 / 82) 0% (0 / 36) 0% (0 / 12) 13.41% (11 / 82)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/lib/retry.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/lib/retry.js

Statements: 10% (5 / 50)      Branches: 0% (0 / 25)      Functions: 0% (0 / 8)      Lines: 10% (5 / 50)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 1011   1               1                                                                         1                     1                                                                                    
var RetryOperation = require('./retry_operation');
 
exports.operation = function(options) {
  var timeouts = exports.timeouts(options);
  return new RetryOperation(timeouts, {
      forever: options && options.forever,
      unref: options && options.unref
  });
};
 
exports.timeouts = function(options) {
  if (options instanceof Array) {
    return [].concat(options);
  }
 
  var opts = {
    retries: 10,
    factor: 2,
    minTimeout: 1 * 1000,
    maxTimeout: Infinity,
    randomize: false
  };
  for (var key in options) {
    opts[key] = options[key];
  }
 
  if (opts.minTimeout > opts.maxTimeout) {
    throw new Error('minTimeout is greater than maxTimeout');
  }
 
  var timeouts = [];
  for (var i = 0; i < opts.retries; i++) {
    timeouts.push(this.createTimeout(i, opts));
  }
 
  if (options && options.forever && !timeouts.length) {
    timeouts.push(this.createTimeout(i, opts));
  }
 
  // sort the array numerically ascending
  timeouts.sort(function(a,b) {
    return a - b;
  });
 
  return timeouts;
};
 
exports.createTimeout = function(attempt, opts) {
  var random = (opts.randomize)
    ? (Math.random() + 1)
    : 1;
 
  var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  timeout = Math.min(timeout, opts.maxTimeout);
 
  return timeout;
};
 
exports.wrap = function(obj, options, methods) {
  if (options instanceof Array) {
    methods = options;
    options = null;
  }
 
  if (!methods) {
    methods = [];
    for (var key in obj) {
      if (typeof obj[key] === 'function') {
        methods.push(key);
      }
    }
  }
 
  for (var i = 0; i < methods.length; i++) {
    var method   = methods[i];
    var original = obj[method];
 
    obj[method] = function retryWrapper() {
      var op       = exports.operation(options);
      var args     = Array.prototype.slice.call(arguments);
      var callback = args.pop();
 
      args.push(function(err) {
        if (op.retry(err)) {
          return;
        }
        if (err) {
          arguments[0] = op.mainError();
        }
        callback.apply(this, arguments);
      });
 
      op.attempt(function() {
        original.apply(obj, args);
      });
    };
    obj[method].options = options;
  }
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/lib/retry_operation.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/retry/lib/retry_operation.js

Statements: 13.41% (11 / 82)      Branches: 0% (0 / 36)      Functions: 0% (0 / 12)      Lines: 13.41% (11 / 82)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 1451                                     1   1                 1                                                                                             1                                           1         1         1   1       1       1                                                  
function RetryOperation(timeouts, options) {
  // Compatibility for the old (timeouts, retryForever) signature
  if (typeof options === 'boolean') {
    options = { forever: options };
  }
 
  this._timeouts = timeouts;
  this._options = options || {};
  this._fn = null;
  this._errors = [];
  this._attempts = 1;
  this._operationTimeout = null;
  this._operationTimeoutCb = null;
  this._timeout = null;
 
  if (this._options.forever) {
    this._cachedTimeouts = this._timeouts.slice(0);
  }
}
module.exports = RetryOperation;
 
RetryOperation.prototype.stop = function() {
  if (this._timeout) {
    clearTimeout(this._timeout);
  }
 
  this._timeouts       = [];
  this._cachedTimeouts = null;
};
 
RetryOperation.prototype.retry = function(err) {
  if (this._timeout) {
    clearTimeout(this._timeout);
  }
 
  if (!err) {
    return false;
  }
 
  this._errors.push(err);
 
  var timeout = this._timeouts.shift();
  if (timeout === undefined) {
    if (this._cachedTimeouts) {
      // retry forever, only keep last error
      this._errors.splice(this._errors.length - 1, this._errors.length);
      this._timeouts = this._cachedTimeouts.slice(0);
      timeout = this._timeouts.shift();
    } else {
      return false;
    }
  }
 
  var self = this;
  var timer = setTimeout(function() {
    self._attempts++;
 
    if (self._operationTimeoutCb) {
      self._timeout = setTimeout(function() {
        self._operationTimeoutCb(self._attempts);
      }, self._operationTimeout);
 
      if (this._options.unref) {
          self._timeout.unref();
      }
    }
 
    self._fn(self._attempts);
  }, timeout);
 
  if (this._options.unref) {
      timer.unref();
  }
 
  return true;
};
 
RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  this._fn = fn;
 
  if (timeoutOps) {
    if (timeoutOps.timeout) {
      this._operationTimeout = timeoutOps.timeout;
    }
    if (timeoutOps.cb) {
      this._operationTimeoutCb = timeoutOps.cb;
    }
  }
 
  var self = this;
  if (this._operationTimeoutCb) {
    this._timeout = setTimeout(function() {
      self._operationTimeoutCb();
    }, self._operationTimeout);
  }
 
  this._fn(this._attempts);
};
 
RetryOperation.prototype.try = function(fn) {
  console.log('Using RetryOperation.try() is deprecated');
  this.attempt(fn);
};
 
RetryOperation.prototype.start = function(fn) {
  console.log('Using RetryOperation.start() is deprecated');
  this.attempt(fn);
};
 
RetryOperation.prototype.start = RetryOperation.prototype.try;
 
RetryOperation.prototype.errors = function() {
  return this._errors;
};
 
RetryOperation.prototype.attempts = function() {
  return this._attempts;
};
 
RetryOperation.prototype.mainError = function() {
  if (this._errors.length === 0) {
    return null;
  }
 
  var counts = {};
  var mainError = null;
  var mainErrorCount = 0;
 
  for (var i = 0; i < this._errors.length; i++) {
    var error = this._errors[i];
    var message = error.message;
    var count = (counts[message] || 0) + 1;
 
    counts[message] = count;
 
    if (count >= mainErrorCount) {
      mainError = error;
      mainErrorCount = count;
    }
  }
 
  return mainError;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/rimraf/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/rimraf/

Statements: 9.91% (21 / 212)      Branches: 0% (0 / 152)      Functions: 0% (0 / 27)      Lines: 9.95% (21 / 211)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/rimraf/
File Statements Branches Functions Lines
rimraf.js 9.91% (21 / 212) 0% (0 / 152) 0% (0 / 27) 9.95% (21 / 211)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/rimraf/rimraf.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/rimraf/rimraf.js

Statements: 9.91% (21 / 212)      Branches: 0% (0 / 152)      Functions: 0% (0 / 27)      Lines: 9.95% (21 / 211)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 3651 1   1 1 1 1   1           1   1   1                                               1                                                       1           1                                                                                                   1                                                                   1                                           1                                                           1                                       1                                                       1                                                                                                                   1                                   1                                                        
module.exports = rimraf
rimraf.sync = rimrafSync
 
var assert = require("assert")
var path = require("path")
var fs = require("fs")
var glob = require("glob")
 
var defaultGlobOpts = {
  nosort: true,
  silent: true
}
 
// for EMFILE handling
var timeout = 0
 
var isWindows = (process.platform === "win32")
 
function defaults (options) {
  var methods = [
    'unlink',
    'chmod',
    'stat',
    'lstat',
    'rmdir',
    'readdir'
  ]
  methods.forEach(function(m) {
    options[m] = options[m] || fs[m]
    m = m + 'Sync'
    options[m] = options[m] || fs[m]
  })
 
  options.maxBusyTries = options.maxBusyTries || 3
  options.emfileWait = options.emfileWait || 1000
  if (options.glob === false) {
    options.disableGlob = true
  }
  options.disableGlob = options.disableGlob || false
  options.glob = options.glob || defaultGlobOpts
}
 
function rimraf (p, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }
 
  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert.equal(typeof cb, 'function', 'rimraf: callback function required')
  assert(options, 'rimraf: invalid options argument provided')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')
 
  defaults(options)
 
  var busyTries = 0
  var errState = null
  var n = 0
 
  if (options.disableGlob || !glob.hasMagic(p))
    return afterGlob(null, [p])
 
  options.lstat(p, function (er, stat) {
    if (!er)
      return afterGlob(null, [p])
 
    glob(p, options.glob, afterGlob)
  })
 
  function next (er) {
    errState = errState || er
    if (--n === 0)
      cb(errState)
  }
 
  function afterGlob (er, results) {
    if (er)
      return cb(er)
 
    n = results.length
    if (n === 0)
      return cb()
 
    results.forEach(function (p) {
      rimraf_(p, options, function CB (er) {
        if (er) {
          if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") &&
              busyTries < options.maxBusyTries) {
            busyTries ++
            var time = busyTries * 100
            // try again, with the same exact callback as this one.
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, time)
          }
 
          // this one won't happen if graceful-fs is used.
          if (er.code === "EMFILE" && timeout < options.emfileWait) {
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, timeout ++)
          }
 
          // already gone
          if (er.code === "ENOENT") er = null
        }
 
        timeout = 0
        next(er)
      })
    })
  }
}
 
// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
 
  // sunos lets the root user unlink directories, which is... weird.
  // so we have to lstat here and make sure it's not a dir.
  options.lstat(p, function (er, st) {
    if (er && er.code === "ENOENT")
      return cb(null)
 
    // Windows can EPERM on stat.  Life is suffering.
    if (er && er.code === "EPERM" && isWindows)
      fixWinEPERM(p, options, er, cb)
 
    if (st && st.isDirectory())
      return rmdir(p, options, er, cb)
 
    options.unlink(p, function (er) {
      if (er) {
        if (er.code === "ENOENT")
          return cb(null)
        if (er.code === "EPERM")
          return (isWindows)
            ? fixWinEPERM(p, options, er, cb)
            : rmdir(p, options, er, cb)
        if (er.code === "EISDIR")
          return rmdir(p, options, er, cb)
      }
      return cb(er)
    })
  })
}
 
function fixWinEPERM (p, options, er, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
  if (er)
    assert(er instanceof Error)
 
  options.chmod(p, 666, function (er2) {
    if (er2)
      cb(er2.code === "ENOENT" ? null : er)
    else
      options.stat(p, function(er3, stats) {
        if (er3)
          cb(er3.code === "ENOENT" ? null : er)
        else if (stats.isDirectory())
          rmdir(p, options, er, cb)
        else
          options.unlink(p, cb)
      })
  })
}
 
function fixWinEPERMSync (p, options, er) {
  assert(p)
  assert(options)
  if (er)
    assert(er instanceof Error)
 
  try {
    options.chmodSync(p, 666)
  } catch (er2) {
    if (er2.code === "ENOENT")
      return
    else
      throw er
  }
 
  try {
    var stats = options.statSync(p)
  } catch (er3) {
    if (er3.code === "ENOENT")
      return
    else
      throw er
  }
 
  if (stats.isDirectory())
    rmdirSync(p, options, er)
  else
    options.unlinkSync(p)
}
 
function rmdir (p, options, originalEr, cb) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
  assert(typeof cb === 'function')
 
  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  options.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}
 
function rmkids(p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
 
  options.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return options.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), options, function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          options.rmdir(p, cb)
      })
    })
  })
}
 
// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
  options = options || {}
  defaults(options)
 
  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert(options, 'rimraf: missing options')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')
 
  var results
 
  if (options.disableGlob || !glob.hasMagic(p)) {
    results = [p]
  } else {
    try {
      options.lstatSync(p)
      results = [p]
    } catch (er) {
      results = glob.sync(p, options.glob)
    }
  }
 
  if (!results.length)
    return
 
  for (var i = 0; i < results.length; i++) {
    var p = results[i]
 
    try {
      var st = options.lstatSync(p)
    } catch (er) {
      if (er.code === "ENOENT")
        return
 
      // Windows can EPERM on stat.  Life is suffering.
      if (er.code === "EPERM" && isWindows)
        fixWinEPERMSync(p, options, er)
    }
 
    try {
      // sunos lets the root user unlink directories, which is... weird.
      if (st && st.isDirectory())
        rmdirSync(p, options, null)
      else
        options.unlinkSync(p)
    } catch (er) {
      if (er.code === "ENOENT")
        return
      if (er.code === "EPERM")
        return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
      if (er.code !== "EISDIR")
        throw er
 
      rmdirSync(p, options, er)
    }
  }
}
 
function rmdirSync (p, options, originalEr) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
 
  try {
    options.rmdirSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "ENOTDIR")
      throw originalEr
    if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
      rmkidsSync(p, options)
  }
}
 
function rmkidsSync (p, options) {
  assert(p)
  assert(options)
  options.readdirSync(p).forEach(function (f) {
    rimrafSync(path.join(p, f), options)
  })
 
  // We only end up here once we got ENOTEMPTY at least once, and
  // at this point, we are guaranteed to have removed all the kids.
  // So, we know that it won't be ENOENT or ENOTDIR or anything else.
  // try really hard to delete stuff on windows, because it has a
  // PROFOUNDLY annoying habit of not closing handles promptly when
  // files are deleted, resulting in spurious ENOTEMPTY errors.
  var retries = isWindows ? 100 : 1
  var i = 0
  do {
    var threw = true
    try {
      var ret = options.rmdirSync(p, options)
      threw = false
      return ret
    } finally {
      if (++i < retries && threw)
        continue
    }
  } while (true)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/semver/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/semver/

Statements: 52.09% (349 / 670)      Branches: 25.96% (95 / 366)      Functions: 47.56% (39 / 82)      Lines: 52.58% (347 / 660)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/semver/
File Statements Branches Functions Lines
semver.js 52.09% (349 / 670) 25.96% (95 / 366) 47.56% (39 / 82) 52.58% (347 / 660)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/semver/semver.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/semver/semver.js

Statements: 52.09% (349 / 670)      Branches: 25.96% (95 / 366)      Functions: 47.56% (39 / 82)      Lines: 52.58% (347 / 660)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 12051     1 1                   1       1   1 1     1 1 1               1 1 1 1             1 1           1 1       1 1             1 1     1 1               1 1     1 1           1 1           1 1                         1 1       1         1       1 1   1 1         1 1 1 1   1 1             1 1             1 1 1 1       1 1   1 1 1 1   1 1 1 1       1 1   1 1 1 1   1 1 1 1     1 1 1 1         1 1       1 1             1 1         1 1           1 1       1 34 34 31     1 1 2     2     2     2 2     2 2           1 1           1 1         1   1 10 3 3     7       7     7     7 7 7   7     7     7 7 7   7     7     7       7 7                     7 7     1 7 7   7     1       1 3 3     3     1 3     3         1                                                               1                                                                                                                                                                                               1 1                         1 1                                                   1   1 1 3 3   3 3 3     3             1 1       1 1       1 1       1 1       1 1 3     1 1       1 1       1 1           1 1           1 1       1 1 1     1 1       1 1       1 1 2     1 1       1 1 3 3                           2 1       3     1 1 3             3     3 3 3   3     3   3     1 1 3 3   3     3 3       3     3     1 3     1 3   3     3     3       1 1 2     2     2     2 2 2     2     2       2     1 2 2   2     1       1 2 2 2   2 2 2   2 2     2     2     2         2 2 3   2           2 3     2       1 1                     1 3 3 3 3 3 3 3 3 3 3     1 8                 1 3 3       1 3 3                                                                 1 3 3       1 3 3 3                                                                                           1 3 3 3       1 3 3 3 3 3 3 3 3   3     3               3   3 1 3 3   3                         3     1 1     1     3             3   3           1 3   3               1                                                         1 2     2 2   2 2 1   1     1 2 3 1     1                                               1     1 1 2 2       2     1 1               1 1               1 1                     1 1         1 1       1 1                                                                                                                                         1 1          
exports = module.exports = SemVer;
 
// The debug function is excluded entirely from the minified version.
/* nomin */ var debug;
/* nomin */ Iif (typeof process === 'object' &&
    /* nomin */ process.env &&
    /* nomin */ process.env.NODE_DEBUG &&
    /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG))
  /* nomin */ debug = function() {
    /* nomin */ var args = Array.prototype.slice.call(arguments, 0);
    /* nomin */ args.unshift('SEMVER');
    /* nomin */ console.log.apply(console, args);
    /* nomin */ };
/* nomin */ else
  /* nomin */ debug = function() {};
 
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
exports.SEMVER_SPEC_VERSION = '2.0.0';
 
var MAX_LENGTH = 256;
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
 
// The actual regexps go on exports.re
var re = exports.re = [];
var src = exports.src = [];
var R = 0;
 
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
 
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
 
var NUMERICIDENTIFIER = R++;
src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
var NUMERICIDENTIFIERLOOSE = R++;
src[NUMERICIDENTIFIERLOOSE] = '[0-9]+';
 
 
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
 
var NONNUMERICIDENTIFIER = R++;
src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
 
 
// ## Main Version
// Three dot-separated numeric identifiers.
 
var MAINVERSION = R++;
src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[NUMERICIDENTIFIER] + ')';
 
var MAINVERSIONLOOSE = R++;
src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[NUMERICIDENTIFIERLOOSE] + ')';
 
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
 
var PRERELEASEIDENTIFIER = R++;
src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +
                            '|' + src[NONNUMERICIDENTIFIER] + ')';
 
var PRERELEASEIDENTIFIERLOOSE = R++;
src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +
                                 '|' + src[NONNUMERICIDENTIFIER] + ')';
 
 
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
 
var PRERELEASE = R++;
src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +
                  '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
 
var PRERELEASELOOSE = R++;
src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +
                       '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))';
 
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
 
var BUILDIDENTIFIER = R++;
src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+';
 
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
 
var BUILD = R++;
src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] +
             '(?:\\.' + src[BUILDIDENTIFIER] + ')*))';
 
 
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
 
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups.  The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
 
var FULL = R++;
var FULLPLAIN = 'v?' + src[MAINVERSION] +
                src[PRERELEASE] + '?' +
                src[BUILD] + '?';
 
src[FULL] = '^' + FULLPLAIN + '$';
 
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] +
                 src[PRERELEASELOOSE] + '?' +
                 src[BUILD] + '?';
 
var LOOSE = R++;
src[LOOSE] = '^' + LOOSEPLAIN + '$';
 
var GTLT = R++;
src[GTLT] = '((?:<|>)?=?)';
 
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
var XRANGEIDENTIFIERLOOSE = R++;
src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
var XRANGEIDENTIFIER = R++;
src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
 
var XRANGEPLAIN = R++;
src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:' + src[PRERELEASE] + ')?' +
                   src[BUILD] + '?' +
                   ')?)?';
 
var XRANGEPLAINLOOSE = R++;
src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:' + src[PRERELEASELOOSE] + ')?' +
                        src[BUILD] + '?' +
                        ')?)?';
 
var XRANGE = R++;
src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
var XRANGELOOSE = R++;
src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$';
 
// Tilde ranges.
// Meaning is "reasonably at or greater than"
var LONETILDE = R++;
src[LONETILDE] = '(?:~>?)';
 
var TILDETRIM = R++;
src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
var tildeTrimReplace = '$1~';
 
var TILDE = R++;
src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
var TILDELOOSE = R++;
src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$';
 
// Caret ranges.
// Meaning is "at least and backwards compatible with"
var LONECARET = R++;
src[LONECARET] = '(?:\\^)';
 
var CARETTRIM = R++;
src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
var caretTrimReplace = '$1^';
 
var CARET = R++;
src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
var CARETLOOSE = R++;
src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$';
 
// A simple gt/lt/eq thing, or just "" to indicate "any version"
var COMPARATORLOOSE = R++;
src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
var COMPARATOR = R++;
src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$';
 
 
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
var COMPARATORTRIM = R++;
src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] +
                      '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')';
 
// this one has to use the /g flag
re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
var comparatorTrimReplace = '$1$2$3';
 
 
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
var HYPHENRANGE = R++;
src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' +
                   '\\s+-\\s+' +
                   '(' + src[XRANGEPLAIN] + ')' +
                   '\\s*$';
 
var HYPHENRANGELOOSE = R++;
src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' +
                        '\\s+-\\s+' +
                        '(' + src[XRANGEPLAINLOOSE] + ')' +
                        '\\s*$';
 
// Star ranges basically just allow anything at all.
var STAR = R++;
src[STAR] = '(<|>)?=?\\s*\\*';
 
// Compile to actual regexp objects.
// All are flag-free, unless they were created above with a flag.
for (var i = 0; i < R; i++) {
  debug(i, src[i]);
  if (!re[i])
    re[i] = new RegExp(src[i]);
}
 
exports.parse = parse;
function parse(version, loose) {
  Iif (version instanceof SemVer)
    return version;
 
  Iif (typeof version !== 'string')
    return null;
 
  Iif (version.length > MAX_LENGTH)
    return null;
 
  var r = loose ? re[LOOSE] : re[FULL];
  Iif (!r.test(version))
    return null;
 
  try {
    return new SemVer(version, loose);
  } catch (er) {
    return null;
  }
}
 
exports.valid = valid;
function valid(version, loose) {
  var v = parse(version, loose);
  return v ? v.version : null;
}
 
 
exports.clean = clean;
function clean(version, loose) {
  var s = parse(version.trim().replace(/^[=v]+/, ''), loose);
  return s ? s.version : null;
}
 
exports.SemVer = SemVer;
 
function SemVer(version, loose) {
  if (version instanceof SemVer) {
    Eif (version.loose === loose)
      return version;
    else
      version = version.version;
  } else Iif (typeof version !== 'string') {
    throw new TypeError('Invalid Version: ' + version);
  }
 
  Iif (version.length > MAX_LENGTH)
    throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
 
  Iif (!(this instanceof SemVer))
    return new SemVer(version, loose);
 
  debug('SemVer', version, loose);
  this.loose = loose;
  var m = version.trim().match(loose ? re[LOOSE] : re[FULL]);
 
  Iif (!m)
    throw new TypeError('Invalid Version: ' + version);
 
  this.raw = version;
 
  // these are actually numbers
  this.major = +m[1];
  this.minor = +m[2];
  this.patch = +m[3];
 
  Iif (this.major > MAX_SAFE_INTEGER || this.major < 0)
    throw new TypeError('Invalid major version')
 
  Iif (this.minor > MAX_SAFE_INTEGER || this.minor < 0)
    throw new TypeError('Invalid minor version')
 
  Iif (this.patch > MAX_SAFE_INTEGER || this.patch < 0)
    throw new TypeError('Invalid patch version')
 
  // numberify any prerelease numeric ids
  Eif (!m[4])
    this.prerelease = [];
  else
    this.prerelease = m[4].split('.').map(function(id) {
      if (/^[0-9]+$/.test(id)) {
        var num = +id;
        if (num >= 0 && num < MAX_SAFE_INTEGER)
          return num;
      }
      return id;
    });
 
  this.build = m[5] ? m[5].split('.') : [];
  this.format();
}
 
SemVer.prototype.format = function() {
  this.version = this.major + '.' + this.minor + '.' + this.patch;
  Iif (this.prerelease.length)
    this.version += '-' + this.prerelease.join('.');
  return this.version;
};
 
SemVer.prototype.toString = function() {
  return this.version;
};
 
SemVer.prototype.compare = function(other) {
  debug('SemVer.compare', this.version, this.loose, other);
  Iif (!(other instanceof SemVer))
    other = new SemVer(other, this.loose);
 
  return this.compareMain(other) || this.comparePre(other);
};
 
SemVer.prototype.compareMain = function(other) {
  Iif (!(other instanceof SemVer))
    other = new SemVer(other, this.loose);
 
  return compareIdentifiers(this.major, other.major) ||
         compareIdentifiers(this.minor, other.minor) ||
         compareIdentifiers(this.patch, other.patch);
};
 
SemVer.prototype.comparePre = function(other) {
  if (!(other instanceof SemVer))
    other = new SemVer(other, this.loose);
 
  // NOT having a prerelease is > having one
  if (this.prerelease.length && !other.prerelease.length)
    return -1;
  else if (!this.prerelease.length && other.prerelease.length)
    return 1;
  else if (!this.prerelease.length && !other.prerelease.length)
    return 0;
 
  var i = 0;
  do {
    var a = this.prerelease[i];
    var b = other.prerelease[i];
    debug('prerelease compare', i, a, b);
    if (a === undefined && b === undefined)
      return 0;
    else if (b === undefined)
      return 1;
    else if (a === undefined)
      return -1;
    else if (a === b)
      continue;
    else
      return compareIdentifiers(a, b);
  } while (++i);
};
 
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
SemVer.prototype.inc = function(release, identifier) {
  switch (release) {
    case 'premajor':
      this.prerelease.length = 0;
      this.patch = 0;
      this.minor = 0;
      this.major++;
      this.inc('pre', identifier);
      break;
    case 'preminor':
      this.prerelease.length = 0;
      this.patch = 0;
      this.minor++;
      this.inc('pre', identifier);
      break;
    case 'prepatch':
      // If this is already a prerelease, it will bump to the next version
      // drop any prereleases that might already exist, since they are not
      // relevant at this point.
      this.prerelease.length = 0;
      this.inc('patch', identifier);
      this.inc('pre', identifier);
      break;
    // If the input is a non-prerelease version, this acts the same as
    // prepatch.
    case 'prerelease':
      if (this.prerelease.length === 0)
        this.inc('patch', identifier);
      this.inc('pre', identifier);
      break;
 
    case 'major':
      // If this is a pre-major version, bump up to the same major version.
      // Otherwise increment major.
      // 1.0.0-5 bumps to 1.0.0
      // 1.1.0 bumps to 2.0.0
      if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0)
        this.major++;
      this.minor = 0;
      this.patch = 0;
      this.prerelease = [];
      break;
    case 'minor':
      // If this is a pre-minor version, bump up to the same minor version.
      // Otherwise increment minor.
      // 1.2.0-5 bumps to 1.2.0
      // 1.2.1 bumps to 1.3.0
      if (this.patch !== 0 || this.prerelease.length === 0)
        this.minor++;
      this.patch = 0;
      this.prerelease = [];
      break;
    case 'patch':
      // If this is not a pre-release version, it will increment the patch.
      // If it is a pre-release it will bump up to the same patch version.
      // 1.2.0-5 patches to 1.2.0
      // 1.2.0 patches to 1.2.1
      if (this.prerelease.length === 0)
        this.patch++;
      this.prerelease = [];
      break;
    // This probably shouldn't be used publicly.
    // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
    case 'pre':
      if (this.prerelease.length === 0)
        this.prerelease = [0];
      else {
        var i = this.prerelease.length;
        while (--i >= 0) {
          if (typeof this.prerelease[i] === 'number') {
            this.prerelease[i]++;
            i = -2;
          }
        }
        if (i === -1) // didn't increment anything
          this.prerelease.push(0);
      }
      if (identifier) {
        // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
        // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
        if (this.prerelease[0] === identifier) {
          if (isNaN(this.prerelease[1]))
            this.prerelease = [identifier, 0];
        } else
          this.prerelease = [identifier, 0];
      }
      break;
 
    default:
      throw new Error('invalid increment argument: ' + release);
  }
  this.format();
  this.raw = this.version;
  return this;
};
 
exports.inc = inc;
function inc(version, release, loose, identifier) {
  if (typeof(loose) === 'string') {
    identifier = loose;
    loose = undefined;
  }
 
  try {
    return new SemVer(version, loose).inc(release, identifier).version;
  } catch (er) {
    return null;
  }
}
 
exports.diff = diff;
function diff(version1, version2) {
  if (eq(version1, version2)) {
    return null;
  } else {
    var v1 = parse(version1);
    var v2 = parse(version2);
    if (v1.prerelease.length || v2.prerelease.length) {
      for (var key in v1) {
        if (key === 'major' || key === 'minor' || key === 'patch') {
          if (v1[key] !== v2[key]) {
            return 'pre'+key;
          }
        }
      }
      return 'prerelease';
    }
    for (var key in v1) {
      if (key === 'major' || key === 'minor' || key === 'patch') {
        if (v1[key] !== v2[key]) {
          return key;
        }
      }
    }
  }
}
 
exports.compareIdentifiers = compareIdentifiers;
 
var numeric = /^[0-9]+$/;
function compareIdentifiers(a, b) {
  var anum = numeric.test(a);
  var bnum = numeric.test(b);
 
  Eif (anum && bnum) {
    a = +a;
    b = +b;
  }
 
  return (anum && !bnum) ? -1 :
         (bnum && !anum) ? 1 :
         a < b ? -1 :
         a > b ? 1 :
         0;
}
 
exports.rcompareIdentifiers = rcompareIdentifiers;
function rcompareIdentifiers(a, b) {
  return compareIdentifiers(b, a);
}
 
exports.major = major;
function major(a, loose) {
  return new SemVer(a, loose).major;
}
 
exports.minor = minor;
function minor(a, loose) {
  return new SemVer(a, loose).minor;
}
 
exports.patch = patch;
function patch(a, loose) {
  return new SemVer(a, loose).patch;
}
 
exports.compare = compare;
function compare(a, b, loose) {
  return new SemVer(a, loose).compare(b);
}
 
exports.compareLoose = compareLoose;
function compareLoose(a, b) {
  return compare(a, b, true);
}
 
exports.rcompare = rcompare;
function rcompare(a, b, loose) {
  return compare(b, a, loose);
}
 
exports.sort = sort;
function sort(list, loose) {
  return list.sort(function(a, b) {
    return exports.compare(a, b, loose);
  });
}
 
exports.rsort = rsort;
function rsort(list, loose) {
  return list.sort(function(a, b) {
    return exports.rcompare(a, b, loose);
  });
}
 
exports.gt = gt;
function gt(a, b, loose) {
  return compare(a, b, loose) > 0;
}
 
exports.lt = lt;
function lt(a, b, loose) {
  return compare(a, b, loose) < 0;
}
 
exports.eq = eq;
function eq(a, b, loose) {
  return compare(a, b, loose) === 0;
}
 
exports.neq = neq;
function neq(a, b, loose) {
  return compare(a, b, loose) !== 0;
}
 
exports.gte = gte;
function gte(a, b, loose) {
  return compare(a, b, loose) >= 0;
}
 
exports.lte = lte;
function lte(a, b, loose) {
  return compare(a, b, loose) <= 0;
}
 
exports.cmp = cmp;
function cmp(a, op, b, loose) {
  var ret;
  switch (op) {
    case '===':
      if (typeof a === 'object') a = a.version;
      if (typeof b === 'object') b = b.version;
      ret = a === b;
      break;
    case '!==':
      if (typeof a === 'object') a = a.version;
      if (typeof b === 'object') b = b.version;
      ret = a !== b;
      break;
    case '': case '=': case '==': ret = eq(a, b, loose); break;
    case '!=': ret = neq(a, b, loose); break;
    case '>': ret = gt(a, b, loose); break;
    case '>=': ret = gte(a, b, loose); break;
    case '<': ret = lt(a, b, loose); break;
    case '<=': ret = lte(a, b, loose); break;
    default: throw new TypeError('Invalid operator: ' + op);
  }
  return ret;
}
 
exports.Comparator = Comparator;
function Comparator(comp, loose) {
  Iif (comp instanceof Comparator) {
    if (comp.loose === loose)
      return comp;
    else
      comp = comp.value;
  }
 
  Iif (!(this instanceof Comparator))
    return new Comparator(comp, loose);
 
  debug('comparator', comp, loose);
  this.loose = loose;
  this.parse(comp);
 
  Iif (this.semver === ANY)
    this.value = '';
  else
    this.value = this.operator + this.semver.version;
 
  debug('comp', this);
}
 
var ANY = {};
Comparator.prototype.parse = function(comp) {
  var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
  var m = comp.match(r);
 
  Iif (!m)
    throw new TypeError('Invalid comparator: ' + comp);
 
  this.operator = m[1];
  Iif (this.operator === '=')
    this.operator = '';
 
  // if it literally is just '>' or '' then allow anything.
  Iif (!m[2])
    this.semver = ANY;
  else
    this.semver = new SemVer(m[2], this.loose);
};
 
Comparator.prototype.toString = function() {
  return this.value;
};
 
Comparator.prototype.test = function(version) {
  debug('Comparator.test', version, this.loose);
 
  Iif (this.semver === ANY)
    return true;
 
  Iif (typeof version === 'string')
    version = new SemVer(version, this.loose);
 
  return cmp(version, this.operator, this.semver, this.loose);
};
 
 
exports.Range = Range;
function Range(range, loose) {
  Iif ((range instanceof Range) && range.loose === loose)
    return range;
 
  Iif (!(this instanceof Range))
    return new Range(range, loose);
 
  this.loose = loose;
 
  // First, split based on boolean or ||
  this.raw = range;
  this.set = range.split(/\s*\|\|\s*/).map(function(range) {
    return this.parseRange(range.trim());
  }, this).filter(function(c) {
    // throw out any that are not relevant for whatever reason
    return c.length;
  });
 
  Iif (!this.set.length) {
    throw new TypeError('Invalid SemVer Range: ' + range);
  }
 
  this.format();
}
 
Range.prototype.format = function() {
  this.range = this.set.map(function(comps) {
    return comps.join(' ').trim();
  }).join('||').trim();
  return this.range;
};
 
Range.prototype.toString = function() {
  return this.range;
};
 
Range.prototype.parseRange = function(range) {
  var loose = this.loose;
  range = range.trim();
  debug('range', range, loose);
  // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
  var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
  range = range.replace(hr, hyphenReplace);
  debug('hyphen replace', range);
  // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
  range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
  debug('comparator trim', range, re[COMPARATORTRIM]);
 
  // `~ 1.2.3` => `~1.2.3`
  range = range.replace(re[TILDETRIM], tildeTrimReplace);
 
  // `^ 1.2.3` => `^1.2.3`
  range = range.replace(re[CARETTRIM], caretTrimReplace);
 
  // normalize spaces
  range = range.split(/\s+/).join(' ');
 
  // At this point, the range is completely trimmed and
  // ready to be split into comparators.
 
  var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
  var set = range.split(' ').map(function(comp) {
    return parseComparator(comp, loose);
  }).join(' ').split(/\s+/);
  Iif (this.loose) {
    // in loose mode, throw out any that are not valid comparators
    set = set.filter(function(comp) {
      return !!comp.match(compRe);
    });
  }
  set = set.map(function(comp) {
    return new Comparator(comp, loose);
  });
 
  return set;
};
 
// Mostly just for testing and legacy API reasons
exports.toComparators = toComparators;
function toComparators(range, loose) {
  return new Range(range, loose).set.map(function(comp) {
    return comp.map(function(c) {
      return c.value;
    }).join(' ').trim().split(' ');
  });
}
 
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
function parseComparator(comp, loose) {
  debug('comp', comp);
  comp = replaceCarets(comp, loose);
  debug('caret', comp);
  comp = replaceTildes(comp, loose);
  debug('tildes', comp);
  comp = replaceXRanges(comp, loose);
  debug('xrange', comp);
  comp = replaceStars(comp, loose);
  debug('stars', comp);
  return comp;
}
 
function isX(id) {
  return !id || id.toLowerCase() === 'x' || id === '*';
}
 
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
function replaceTildes(comp, loose) {
  return comp.trim().split(/\s+/).map(function(comp) {
    return replaceTilde(comp, loose);
  }).join(' ');
}
 
function replaceTilde(comp, loose) {
  var r = loose ? re[TILDELOOSE] : re[TILDE];
  return comp.replace(r, function(_, M, m, p, pr) {
    debug('tilde', comp, _, M, m, p, pr);
    var ret;
 
    if (isX(M))
      ret = '';
    else if (isX(m))
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    else if (isX(p))
      // ~1.2 == >=1.2.0 <1.3.0
      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
    else if (pr) {
      debug('replaceTilde pr', pr);
      if (pr.charAt(0) !== '-')
        pr = '-' + pr;
      ret = '>=' + M + '.' + m + '.' + p + pr +
            ' <' + M + '.' + (+m + 1) + '.0';
    } else
      // ~1.2.3 == >=1.2.3 <1.3.0
      ret = '>=' + M + '.' + m + '.' + p +
            ' <' + M + '.' + (+m + 1) + '.0';
 
    debug('tilde return', ret);
    return ret;
  });
}
 
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
// ^1.2.3 --> >=1.2.3 <2.0.0
// ^1.2.0 --> >=1.2.0 <2.0.0
function replaceCarets(comp, loose) {
  return comp.trim().split(/\s+/).map(function(comp) {
    return replaceCaret(comp, loose);
  }).join(' ');
}
 
function replaceCaret(comp, loose) {
  debug('caret', comp, loose);
  var r = loose ? re[CARETLOOSE] : re[CARET];
  return comp.replace(r, function(_, M, m, p, pr) {
    debug('caret', comp, _, M, m, p, pr);
    var ret;
 
    if (isX(M))
      ret = '';
    else if (isX(m))
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    else if (isX(p)) {
      if (M === '0')
        ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
      else
        ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
    } else if (pr) {
      debug('replaceCaret pr', pr);
      if (pr.charAt(0) !== '-')
        pr = '-' + pr;
      if (M === '0') {
        if (m === '0')
          ret = '>=' + M + '.' + m + '.' + p + pr +
                ' <' + M + '.' + m + '.' + (+p + 1);
        else
          ret = '>=' + M + '.' + m + '.' + p + pr +
                ' <' + M + '.' + (+m + 1) + '.0';
      } else
        ret = '>=' + M + '.' + m + '.' + p + pr +
              ' <' + (+M + 1) + '.0.0';
    } else {
      debug('no pr');
      if (M === '0') {
        if (m === '0')
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + m + '.' + (+p + 1);
        else
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + (+m + 1) + '.0';
      } else
        ret = '>=' + M + '.' + m + '.' + p +
              ' <' + (+M + 1) + '.0.0';
    }
 
    debug('caret return', ret);
    return ret;
  });
}
 
function replaceXRanges(comp, loose) {
  debug('replaceXRanges', comp, loose);
  return comp.split(/\s+/).map(function(comp) {
    return replaceXRange(comp, loose);
  }).join(' ');
}
 
function replaceXRange(comp, loose) {
  comp = comp.trim();
  var r = loose ? re[XRANGELOOSE] : re[XRANGE];
  return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
    debug('xRange', comp, ret, gtlt, M, m, p, pr);
    var xM = isX(M);
    var xm = xM || isX(m);
    var xp = xm || isX(p);
    var anyX = xp;
 
    Iif (gtlt === '=' && anyX)
      gtlt = '';
 
    Iif (xM) {
      if (gtlt === '>' || gtlt === '<') {
        // nothing is allowed
        ret = '<0.0.0';
      } else {
        // nothing is forbidden
        ret = '*';
      }
    } else Eif (gtlt && anyX) {
      // replace X with 0
      if (xm)
        m = 0;
      Eif (xp)
        p = 0;
 
      Iif (gtlt === '>') {
        // >1 => >=2.0.0
        // >1.2 => >=1.3.0
        // >1.2.3 => >= 1.2.4
        gtlt = '>=';
        if (xm) {
          M = +M + 1;
          m = 0;
          p = 0;
        } else if (xp) {
          m = +m + 1;
          p = 0;
        }
      } else if (gtlt === '<=') {
        // <=0.7.x is actually <0.8.0, since any 0.7.x should
        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
        gtlt = '<';
        Iif (xm)
          M = +M + 1;
        else
          m = +m + 1;
      }
 
      ret = gtlt + M + '.' + m + '.' + p;
    } else if (xm) {
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    } else if (xp) {
      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
    }
 
    debug('xRange return', ret);
 
    return ret;
  });
}
 
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
function replaceStars(comp, loose) {
  debug('replaceStars', comp, loose);
  // Looseness is ignored here.  star is always as loose as it gets!
  return comp.trim().replace(re[STAR], '');
}
 
// This function is passed to string.replace(re[HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0
function hyphenReplace($0,
                       from, fM, fm, fp, fpr, fb,
                       to, tM, tm, tp, tpr, tb) {
 
  if (isX(fM))
    from = '';
  else if (isX(fm))
    from = '>=' + fM + '.0.0';
  else if (isX(fp))
    from = '>=' + fM + '.' + fm + '.0';
  else
    from = '>=' + from;
 
  if (isX(tM))
    to = '';
  else if (isX(tm))
    to = '<' + (+tM + 1) + '.0.0';
  else if (isX(tp))
    to = '<' + tM + '.' + (+tm + 1) + '.0';
  else if (tpr)
    to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
  else
    to = '<=' + to;
 
  return (from + ' ' + to).trim();
}
 
 
// if ANY of the sets match ALL of its comparators, then pass
Range.prototype.test = function(version) {
  Iif (!version)
    return false;
 
  Eif (typeof version === 'string')
    version = new SemVer(version, this.loose);
 
  for (var i = 0; i < this.set.length; i++) {
    if (testSet(this.set[i], version))
      return true;
  }
  return false;
};
 
function testSet(set, version) {
  for (var i = 0; i < set.length; i++) {
    if (!set[i].test(version))
      return false;
  }
 
  Iif (version.prerelease.length) {
    // Find the set of versions that are allowed to have prereleases
    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
    // That should allow `1.2.3-pr.2` to pass.
    // However, `1.2.4-alpha.notready` should NOT be allowed,
    // even though it's within the range set by the comparators.
    for (var i = 0; i < set.length; i++) {
      debug(set[i].semver);
      if (set[i].semver === ANY)
        continue;
 
      if (set[i].semver.prerelease.length > 0) {
        var allowed = set[i].semver;
        if (allowed.major === version.major &&
            allowed.minor === version.minor &&
            allowed.patch === version.patch)
          return true;
      }
    }
 
    // Version has a -pre, but it's not one of the ones we like.
    return false;
  }
 
  return true;
}
 
exports.satisfies = satisfies;
function satisfies(version, range, loose) {
  try {
    range = new Range(range, loose);
  } catch (er) {
    return false;
  }
  return range.test(version);
}
 
exports.maxSatisfying = maxSatisfying;
function maxSatisfying(versions, range, loose) {
  return versions.filter(function(version) {
    return satisfies(version, range, loose);
  }).sort(function(a, b) {
    return rcompare(a, b, loose);
  })[0] || null;
}
 
exports.minSatisfying = minSatisfying;
function minSatisfying(versions, range, loose) {
  return versions.filter(function(version) {
    return satisfies(version, range, loose);
  }).sort(function(a, b) {
    return compare(a, b, loose);
  })[0] || null;
}
 
exports.validRange = validRange;
function validRange(range, loose) {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return new Range(range, loose).range || '*';
  } catch (er) {
    return null;
  }
}
 
// Determine if version is less than all the versions possible in the range
exports.ltr = ltr;
function ltr(version, range, loose) {
  return outside(version, range, '<', loose);
}
 
// Determine if version is greater than all the versions possible in the range.
exports.gtr = gtr;
function gtr(version, range, loose) {
  return outside(version, range, '>', loose);
}
 
exports.outside = outside;
function outside(version, range, hilo, loose) {
  version = new SemVer(version, loose);
  range = new Range(range, loose);
 
  var gtfn, ltefn, ltfn, comp, ecomp;
  switch (hilo) {
    case '>':
      gtfn = gt;
      ltefn = lte;
      ltfn = lt;
      comp = '>';
      ecomp = '>=';
      break;
    case '<':
      gtfn = lt;
      ltefn = gte;
      ltfn = gt;
      comp = '<';
      ecomp = '<=';
      break;
    default:
      throw new TypeError('Must provide a hilo val of "<" or ">"');
  }
 
  // If it satisifes the range it is not outside
  if (satisfies(version, range, loose)) {
    return false;
  }
 
  // From now on, variable terms are as if we're in "gtr" mode.
  // but note that everything is flipped for the "ltr" function.
 
  for (var i = 0; i < range.set.length; ++i) {
    var comparators = range.set[i];
 
    var high = null;
    var low = null;
 
    comparators.forEach(function(comparator) {
      if (comparator.semver === ANY) {
        comparator = new Comparator('>=0.0.0')
      }
      high = high || comparator;
      low = low || comparator;
      if (gtfn(comparator.semver, high.semver, loose)) {
        high = comparator;
      } else if (ltfn(comparator.semver, low.semver, loose)) {
        low = comparator;
      }
    });
 
    // If the edge version comparator has a operator then our version
    // isn't outside it
    if (high.operator === comp || high.operator === ecomp) {
      return false;
    }
 
    // If the lowest version comparator has an operator and our version
    // is less than it then it isn't higher than the range
    if ((!low.operator || low.operator === comp) &&
        ltefn(version, low.semver)) {
      return false;
    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
      return false;
    }
  }
  return true;
}
 
exports.prerelease = prerelease;
function prerelease(version, loose) {
  var parsed = parse(version, loose);
  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sha/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sha/

Statements: 17.11% (13 / 76)      Branches: 2.78% (1 / 36)      Functions: 0% (0 / 11)      Lines: 18.84% (13 / 69)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sha/
File Statements Branches Functions Lines
index.js 17.11% (13 / 76) 2.78% (1 / 36) 0% (0 / 11) 18.84% (13 / 69)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sha/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sha/index.js

Statements: 17.11% (13 / 76)      Branches: 2.78% (1 / 36)      Functions: 0% (0 / 11)      Lines: 18.84% (13 / 69)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108    1 1 1   1 1 1 1 1   1                                   1                                     1                                                   1                 1                                              
'use strict'
 
var Transform = require('stream').Transform || require('readable-stream').Transform
var crypto = require('crypto')
var fs = require('graceful-fs')
 
exports.check = check
exports.checkSync = checkSync
exports.get = get
exports.getSync = getSync
exports.stream = stream
 
function check(file, expected, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = undefined
  }
  expected = expected.toLowerCase().trim()
  get(file, options, function (er, actual) {
    if (er) {
      if (er.message) er.message += ' while getting shasum for ' + file
      return cb(er)
    }
    if (actual === expected) return cb(null)
    cb(new Error(
        'shasum check failed for ' + file + '\n'
      + 'Expected: ' + expected + '\n'
      + 'Actual:   ' + actual))
  })
}
function checkSync(file, expected, options) {
  expected = expected.toLowerCase().trim()
  var actual
  try {
    actual = getSync(file, options)
  } catch (er) {
    if (er.message) er.message += ' while getting shasum for ' + file
    throw er
  }
  if (actual !== expected) {
    var ex = new Error(
        'shasum check failed for ' + file + '\n'
      + 'Expected: ' + expected + '\n'
      + 'Actual:   ' + actual)
    throw ex
  }
}
 
 
function get(file, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = undefined
  }
  options = options || {}
  var algorithm = options.algorithm || 'sha1'
  var hash = crypto.createHash(algorithm)
  var source = fs.createReadStream(file)
  var errState = null
  source
    .on('error', function (er) {
      if (errState) return
      return cb(errState = er)
    })
    .on('data', function (chunk) {
      if (errState) return
      hash.update(chunk)
    })
    .on('end', function () {
      if (errState) return
      var actual = hash.digest("hex").toLowerCase().trim()
      cb(null, actual)
    })
}
 
function getSync(file, options) {
  options = options || {}
  var algorithm = options.algorithm || 'sha1'
  var hash = crypto.createHash(algorithm)
  var source = fs.readFileSync(file)
  hash.update(source)
  return hash.digest("hex").toLowerCase().trim()
}
 
function stream(expected, options) {
  expected = expected.toLowerCase().trim()
  options = options || {}
  var algorithm = options.algorithm || 'sha1'
  var hash = crypto.createHash(algorithm)
 
  var stream = new Transform()
  stream._transform = function (chunk, encoding, callback) {
    hash.update(chunk)
    stream.push(chunk)
    callback()
  }
  stream._flush = function (cb) {
    var actual = hash.digest("hex").toLowerCase().trim()
    if (actual === expected) return cb(null)
    cb(new Error(
        'shasum check failed for:\n'
      + '  Expected: ' + expected + '\n'
      + '  Actual:   ' + actual))
    this.push(null)
  }
  return stream
}
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/

Statements: 19.7% (13 / 66)      Branches: 0% (0 / 40)      Functions: 0% (0 / 13)      Lines: 23.08% (12 / 52)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/slide/lib/
File Statements Branches Functions Lines
async-map.js 9.38% (3 / 32) 0% (0 / 22) 0% (0 / 7) 13.04% (3 / 23)
bind-actor.js 18.18% (2 / 11) 0% (0 / 4) 0% (0 / 2) 18.18% (2 / 11)
chain.js 25% (5 / 20) 0% (0 / 14) 0% (0 / 4) 26.67% (4 / 15)
slide.js 100% (3 / 3) 100% (0 / 0) 100% (0 / 0) 100% (3 / 3)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/async-map.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/async-map.js

Statements: 9.38% (3 / 32)      Branches: 0% (0 / 22)      Functions: 0% (0 / 7)      Lines: 13.04% (3 / 23)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                      1   1                           1                                                        
 
/*
usage:
 
// do something to a list of things
asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing.foo, cb) }, cb)
// do more than one thing to each item
asyncMap(list, fooFn, barFn, cb)
 
*/
 
module.exports = asyncMap
 
function asyncMap () {
  var steps = Array.prototype.slice.call(arguments)
    , list = steps.shift() || []
    , cb_ = steps.pop()
  if (typeof cb_ !== "function") throw new Error(
    "No callback provided to asyncMap")
  if (!list) return cb_(null, [])
  if (!Array.isArray(list)) list = [list]
  var n = steps.length
    , data = [] // 2d array
    , errState = null
    , l = list.length
    , a = l * n
  if (!a) return cb_(null, [])
  function cb (er) {
    if (er && !errState) errState = er
 
    var argLen = arguments.length
    for (var i = 1; i < argLen; i ++) if (arguments[i] !== undefined) {
      data[i - 1] = (data[i - 1] || []).concat(arguments[i])
    }
    // see if any new things have been added.
    if (list.length > l) {
      var newList = list.slice(l)
      a += (list.length - l) * n
      l = list.length
      process.nextTick(function () {
        newList.forEach(function (ar) {
          steps.forEach(function (fn) { fn(ar, cb) })
        })
      })
    }
 
    if (--a === 0) cb_.apply(null, [errState].concat(data))
  }
  // expect the supplied cb function to be called
  // "n" times for each thing in the array.
  list.forEach(function (ar) {
    steps.forEach(function (fn) { fn(ar, cb) })
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/bind-actor.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/bind-actor.js

Statements: 18.18% (2 / 11)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 18.18% (2 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 181 1                                
module.exports = bindActor
function bindActor () {
  var args = 
        Array.prototype.slice.call
        (arguments) // jswtf.
    , obj = null
    , fn
  if (typeof args[0] === "object") {
    obj = args.shift()
    fn = args.shift()
    if (typeof fn === "string")
      fn = obj[ fn ]
  } else fn = args.shift()
  return function (cb) {
    fn.apply(obj, args.concat(cb)) }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/chain.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/chain.js

Statements: 25% (5 / 20)      Branches: 0% (0 / 14)      Functions: 0% (0 / 4)      Lines: 26.67% (4 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 221 1 1 1                                    
module.exports = chain
var bindActor = require("./bind-actor.js")
chain.first = {} ; chain.last = {}
function chain (things, cb) {
  var res = []
  ;(function LOOP (i, len) {
    if (i >= len) return cb(null,res)
    if (Array.isArray(things[i]))
      things[i] = bindActor.apply(null,
        things[i].map(function(i){
          return (i===chain.first) ? res[0]
           : (i===chain.last)
             ? res[res.length - 1] : i }))
    if (!things[i]) return LOOP(i + 1, len)
    things[i](function (er, data) {
      if (er) return cb(er, res)
      if (data !== undefined) res = res.concat(data)
      LOOP(i + 1, len)
    })
  })(0, things.length) }
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/slide.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/slide/lib/slide.js

Statements: 100% (3 / 3)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 51 1 1    
exports.asyncMap = require("./async-map")
exports.bindActor = require("./bind-actor")
exports.chain = require("./chain")
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-object/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-object/lib/

Statements: 20% (1 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 20% (1 / 5)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-object/lib/
File Statements Branches Functions Lines
sorted-object.js 20% (1 / 5) 100% (0 / 0) 0% (0 / 2) 20% (1 / 5)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-object/lib/sorted-object.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-object/lib/sorted-object.js

Statements: 20% (1 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 20% (1 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13    1                    
"use strict";
 
module.exports = function (input) {
    var output = {};
 
    Object.keys(input).sort().forEach(function (key) {
        output[key] = input[key];
    });
 
    return output;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/

Statements: 12.2% (5 / 41)      Branches: 0% (0 / 24)      Functions: 0% (0 / 6)      Lines: 14.29% (5 / 35)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/
File Statements Branches Functions Lines
index.js 12.2% (5 / 41) 0% (0 / 24) 0% (0 / 6) 14.29% (5 / 35)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/index.js

Statements: 12.2% (5 / 41)      Branches: 0% (0 / 24)      Functions: 0% (0 / 6)      Lines: 14.29% (5 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 611 1   1       1                                                                                                     1    
var iterate = require('stream-iterate')
var from = require('from2')
 
var defaultKey = function (val) {
  return val.key || val
}
 
var union = function (streamA, streamB, toKey) {
  var readA = iterate(streamA)
  var readB = iterate(streamB)
 
  if (!toKey) toKey = defaultKey
 
  var stream = from.obj(function loop (size, cb) {
    readA(function (err, dataA, nextA) {
      if (err) return cb(err)
      readB(function (err, dataB, nextB) {
        if (err) return cb(err)
 
        if (!dataA && !dataB) return cb(null, null)
 
        if (!dataA) {
          nextB()
          return cb(null, dataB)
        }
 
        if (!dataB) {
          nextA()
          return cb(null, dataA)
        }
 
        var keyA = toKey(dataA)
        var keyB = toKey(dataB)
 
        if (keyA === keyB) {
          nextB()
          return loop(size, cb)
        }
 
        if (keyA < keyB) {
          nextA()
          return cb(null, dataA)
        }
 
        nextB()
        cb(null, dataB)
      })
    })
  })
 
  stream.on('close', function () {
    if (streamA.destroy) streamA.destroy()
    if (streamB.destroy) streamB.destroy()
  })
 
  return stream
}
 
module.exports = union
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/

Statements: 31.88% (22 / 69)      Branches: 8.33% (3 / 36)      Functions: 18.18% (2 / 11)      Lines: 36.67% (22 / 60)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/
File Statements Branches Functions Lines
index.js 31.88% (22 / 69) 8.33% (3 / 36) 18.18% (2 / 11) 36.67% (22 / 60)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/index.js

Statements: 31.88% (22 / 69)      Branches: 8.33% (3 / 36)      Functions: 18.18% (2 / 11)      Lines: 36.67% (22 / 60)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 951 1   1   1 1   1   1             1                         1 1         1   1 1             1 1           1                 1                     1     1                         1 1 1      
var Readable = require('readable-stream').Readable
var inherits = require('inherits')
 
module.exports = from2
 
from2.ctor = ctor
from2.obj = obj
 
var Proto = ctor()
 
function toFunction(list) {
  list = list.slice()
  return function (_, cb) {
    cb(null, list.length ? list.shift() : null)
  }
}
 
function from2(opts, read) {
  if (typeof opts !== 'object' || Array.isArray(opts)) {
    read = opts
    opts = {}
  }
  
  if (Array.isArray(read)) read = toFunction(read)
 
  var rs = new Proto(opts)
  rs._from = read
  return rs
}
 
function ctor(opts, read) {
  Iif (typeof opts === 'function') {
    read = opts
    opts = {}
  }
 
  opts = defaults(opts)
 
  inherits(Class, Readable)
  function Class(override) {
    if (!(this instanceof Class)) return new Class(override)
    this._reading = false
    this.destroyed = false
    Readable.call(this, override || opts)
  }
 
  Class.prototype._from = read
  Class.prototype._read = function(size) {
    var self = this
 
    if (this._reading || this.destroyed) return
    this._reading = true
    this._from(size, check)
    function check(err, data) {
      if (self.destroyed) return
      if (err) return self.destroy(err)
      if (data === null) return self.push(null)
      self._reading = false
      if (self.push(data)) self._read()
    }
  }
 
  Class.prototype.destroy = function(err) {
    if (this.destroyed) return
    this.destroyed = true
 
    var self = this
    process.nextTick(function() {
      if (err) self.emit('error', err)
      self.emit('close')
    })
  }
 
  return Class
}
 
function obj(opts, read) {
  if (typeof opts === 'function' || Array.isArray(opts)) {
    read = opts
    opts = {}
  }
 
  opts = defaults(opts)
  opts.objectMode = true
  opts.highWaterMark = 16
 
  return from2(opts, read)
}
 
function defaults(opts) {
  opts = opts || {}
  return opts
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/

Statements: 88.89% (8 / 9)      Branches: 75% (3 / 4)      Functions: 100% (0 / 0)      Lines: 88.89% (8 / 9)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/
File Statements Branches Functions Lines
readable.js 88.89% (8 / 9) 75% (3 / 4) 100% (0 / 0) 88.89% (8 / 9)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/readable.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/readable.js

Statements: 88.89% (8 / 9)      Branches: 75% (3 / 4)      Functions: 100% (0 / 0)      Lines: 88.89% (8 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 121 1 1 1 1 1 1 1        
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = require('stream');
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
Iif (!process.browser && process.env.READABLE_STREAM === 'disable') {
  module.exports = require('stream');
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/

Statements: 14.8% (123 / 831)      Branches: 1.41% (7 / 497)      Functions: 1.96% (2 / 102)      Lines: 14.89% (123 / 826)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/
File Statements Branches Functions Lines
_stream_duplex.js 44.12% (15 / 34) 13.64% (3 / 22) 40% (2 / 5) 45.45% (15 / 33)
_stream_passthrough.js 63.64% (7 / 11) 0% (0 / 2) 0% (0 / 2) 63.64% (7 / 11)
_stream_readable.js 11.38% (56 / 492) 1.23% (4 / 325) 0% (0 / 53) 11.48% (56 / 488)
_stream_transform.js 18.31% (13 / 71) 0% (0 / 32) 0% (0 / 11) 18.31% (13 / 71)
_stream_writable.js 14.35% (32 / 223) 0% (0 / 116) 0% (0 / 31) 14.35% (32 / 223)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_duplex.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_duplex.js

Statements: 44.12% (15 / 34)      Branches: 13.64% (3 / 22)      Functions: 40% (2 / 5)      Lines: 45.45% (15 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91                                                    1     1                 1 1     1 1   1   1 7 6     1                                         1                     1 1 7        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
 
module.exports = Duplex;
 
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) keys.push(key);
  return keys;
}
/*</replacement>*/
 
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
 
util.inherits(Duplex, Readable);
 
forEach(objectKeys(Writable.prototype), function(method) {
  if (!Duplex.prototype[method])
    Duplex.prototype[method] = Writable.prototype[method];
});
 
function Duplex(options) {
  if (!(this instanceof Duplex))
    return new Duplex(options);
 
  Readable.call(this, options);
  Writable.call(this, options);
 
  if (options && options.readable === false)
    this.readable = false;
 
  if (options && options.writable === false)
    this.writable = false;
 
  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false)
    this.allowHalfOpen = false;
 
  this.once('end', onend);
}
 
// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended)
    return;
 
  // no more data can be written.
  // But allow more writes to happen in this tick.
  process.nextTick(this.end.bind(this));
}
 
function forEach (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_passthrough.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_passthrough.js

Statements: 63.64% (7 / 11)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 63.64% (7 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                                  1   1     1 1     1   1             1        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
 
module.exports = PassThrough;
 
var Transform = require('./_stream_transform');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
util.inherits(PassThrough, Transform);
 
function PassThrough(options) {
  if (!(this instanceof PassThrough))
    return new PassThrough(options);
 
  Transform.call(this, options);
}
 
PassThrough.prototype._transform = function(chunk, encoding, cb) {
  cb(null, chunk);
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_readable.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_readable.js

Statements: 11.38% (56 / 492)      Branches: 1.23% (4 / 325)      Functions: 0% (0 / 53)      Lines: 11.48% (56 / 488)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953                                          1     1         1     1   1     1         1     1 1     1       1 1 1             1   1                                                                                                                                       1                                   1                             1         1                                                                                                               1               1                 1 1                       1                                                                           1                                                                                                                                                                                                                                     1                       1                                 1                             1                         1                 1                                     1       1                                                         1             1                       1                                             1                         1                                     1         1             1                                 1                           1                                                                                                                 1                                                         1       1                           1                 1               1                   1                         1                                                                                                                           1       1                                                                                                                               1                                         1           1              
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
module.exports = Readable;
 
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
 
 
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
 
Readable.ReadableState = ReadableState;
 
var EE = require('events').EventEmitter;
 
/*<replacement>*/
Iif (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/
 
var Stream = require('stream');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var StringDecoder;
 
 
/*<replacement>*/
var debug = require('util');
Eif (debug && debug.debuglog) {
  debug = debug.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/
 
 
util.inherits(Readable, Stream);
 
function ReadableState(options, stream) {
  var Duplex = require('./_stream_duplex');
 
  options = options || {};
 
  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  var defaultHwm = options.objectMode ? 16 : 16 * 1024;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  this.buffer = [];
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
 
 
  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;
 
  if (stream instanceof Duplex)
    this.objectMode = this.objectMode || !!options.readableObjectMode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // when piping, we only care about 'readable' events that happen
  // after read()ing all the bytes and not getting any pushback.
  this.ranOut = false;
 
  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;
 
  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;
 
  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder)
      StringDecoder = require('string_decoder/').StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}
 
function Readable(options) {
  var Duplex = require('./_stream_duplex');
 
  if (!(this instanceof Readable))
    return new Readable(options);
 
  this._readableState = new ReadableState(options, this);
 
  // legacy
  this.readable = true;
 
  Stream.call(this);
}
 
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
  var state = this._readableState;
 
  if (util.isString(chunk) && !state.objectMode) {
    encoding = encoding || state.defaultEncoding;
    if (encoding !== state.encoding) {
      chunk = new Buffer(chunk, encoding);
      encoding = '';
    }
  }
 
  return readableAddChunk(this, state, chunk, encoding, false);
};
 
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
  var state = this._readableState;
  return readableAddChunk(this, state, chunk, '', true);
};
 
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  var er = chunkInvalid(state, chunk);
  if (er) {
    stream.emit('error', er);
  } else if (util.isNullOrUndefined(chunk)) {
    state.reading = false;
    if (!state.ended)
      onEofChunk(stream, state);
  } else if (state.objectMode || chunk && chunk.length > 0) {
    if (state.ended && !addToFront) {
      var e = new Error('stream.push() after EOF');
      stream.emit('error', e);
    } else if (state.endEmitted && addToFront) {
      var e = new Error('stream.unshift() after end event');
      stream.emit('error', e);
    } else {
      if (state.decoder && !addToFront && !encoding)
        chunk = state.decoder.write(chunk);
 
      if (!addToFront)
        state.reading = false;
 
      // if we want the data now, just emit it.
      if (state.flowing && state.length === 0 && !state.sync) {
        stream.emit('data', chunk);
        stream.read(0);
      } else {
        // update the buffer info.
        state.length += state.objectMode ? 1 : chunk.length;
        if (addToFront)
          state.buffer.unshift(chunk);
        else
          state.buffer.push(chunk);
 
        if (state.needReadable)
          emitReadable(stream);
      }
 
      maybeReadMore(stream, state);
    }
  } else if (!addToFront) {
    state.reading = false;
  }
 
  return needMoreData(state);
}
 
 
 
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended &&
         (state.needReadable ||
          state.length < state.highWaterMark ||
          state.length === 0);
}
 
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
  if (!StringDecoder)
    StringDecoder = require('string_decoder/').StringDecoder;
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
  return this;
};
 
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2
    n--;
    for (var p = 1; p < 32; p <<= 1) n |= n >> p;
    n++;
  }
  return n;
}
 
function howMuchToRead(n, state) {
  if (state.length === 0 && state.ended)
    return 0;
 
  if (state.objectMode)
    return n === 0 ? 0 : 1;
 
  if (isNaN(n) || util.isNull(n)) {
    // only flow one buffer at a time
    if (state.flowing && state.buffer.length)
      return state.buffer[0].length;
    else
      return state.length;
  }
 
  if (n <= 0)
    return 0;
 
  // If we're asking for more than the target buffer level,
  // then raise the water mark.  Bump up to the next highest
  // power of 2, to prevent increasing it excessively in tiny
  // amounts.
  if (n > state.highWaterMark)
    state.highWaterMark = roundUpToNextPowerOf2(n);
 
  // don't have that much.  return null, unless we've ended.
  if (n > state.length) {
    if (!state.ended) {
      state.needReadable = true;
      return 0;
    } else
      return state.length;
  }
 
  return n;
}
 
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
  debug('read', n);
  var state = this._readableState;
  var nOrig = n;
 
  if (!util.isNumber(n) || n > 0)
    state.emittedReadable = false;
 
  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 &&
      state.needReadable &&
      (state.length >= state.highWaterMark || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended)
      endReadable(this);
    else
      emitReadable(this);
    return null;
  }
 
  n = howMuchToRead(n, state);
 
  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0)
      endReadable(this);
    return null;
  }
 
  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.
 
  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);
 
  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }
 
  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  }
 
  if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0)
      state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
  }
 
  // If _read pushed data synchronously, then `reading` will be false,
  // and we need to re-evaluate how much data we can return to the user.
  if (doRead && !state.reading)
    n = howMuchToRead(nOrig, state);
 
  var ret;
  if (n > 0)
    ret = fromList(n, state);
  else
    ret = null;
 
  if (util.isNull(ret)) {
    state.needReadable = true;
    n = 0;
  }
 
  state.length -= n;
 
  // If we have nothing in the buffer, then we want to know
  // as soon as we *do* get something into the buffer.
  if (state.length === 0 && !state.ended)
    state.needReadable = true;
 
  // If we tried to read() past the EOF, then emit end on the next tick.
  if (nOrig !== n && state.ended && state.length === 0)
    endReadable(this);
 
  if (!util.isNull(ret))
    this.emit('data', ret);
 
  return ret;
};
 
function chunkInvalid(state, chunk) {
  var er = null;
  if (!util.isBuffer(chunk) &&
      !util.isString(chunk) &&
      !util.isNullOrUndefined(chunk) &&
      !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}
 
 
function onEofChunk(stream, state) {
  if (state.decoder && !state.ended) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;
 
  // emit 'readable' now to make sure it gets picked up.
  emitReadable(stream);
}
 
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    if (state.sync)
      process.nextTick(function() {
        emitReadable_(stream);
      });
    else
      emitReadable_(stream);
  }
}
 
function emitReadable_(stream) {
  debug('emit readable');
  stream.emit('readable');
  flow(stream);
}
 
 
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    process.nextTick(function() {
      maybeReadMore_(stream, state);
    });
  }
}
 
function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended &&
         state.length < state.highWaterMark) {
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;
    else
      len = state.length;
  }
  state.readingMore = false;
}
 
// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
  this.emit('error', new Error('not implemented'));
};
 
Readable.prototype.pipe = function(dest, pipeOpts) {
  var src = this;
  var state = this._readableState;
 
  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
 
  var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
              dest !== process.stdout &&
              dest !== process.stderr;
 
  var endFn = doEnd ? onend : cleanup;
  if (state.endEmitted)
    process.nextTick(endFn);
  else
    src.once('end', endFn);
 
  dest.on('unpipe', onunpipe);
  function onunpipe(readable) {
    debug('onunpipe');
    if (readable === src) {
      cleanup();
    }
  }
 
  function onend() {
    debug('onend');
    dest.end();
  }
 
  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);
 
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', cleanup);
    src.removeListener('data', ondata);
 
    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain &&
        (!dest._writableState || dest._writableState.needDrain))
      ondrain();
  }
 
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    var ret = dest.write(chunk);
    if (false === ret) {
      debug('false write response, pause',
            src._readableState.awaitDrain);
      src._readableState.awaitDrain++;
      src.pause();
    }
  }
 
  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EE.listenerCount(dest, 'error') === 0)
      dest.emit('error', er);
  }
  // This is a brutally ugly hack to make sure that our error handler
  // is attached before any userland ones.  NEVER DO THIS.
  if (!dest._events || !dest._events.error)
    dest.on('error', onerror);
  else if (isArray(dest._events.error))
    dest._events.error.unshift(onerror);
  else
    dest._events.error = [onerror, dest._events.error];
 
 
 
  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);
 
  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }
 
  // tell the dest that it's being piped to
  dest.emit('pipe', src);
 
  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }
 
  return dest;
};
 
function pipeOnDrain(src) {
  return function() {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain)
      state.awaitDrain--;
    if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}
 
 
Readable.prototype.unpipe = function(dest) {
  var state = this._readableState;
 
  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0)
    return this;
 
  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes)
      return this;
 
    if (!dest)
      dest = state.pipes;
 
    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest)
      dest.emit('unpipe', this);
    return this;
  }
 
  // slow case. multiple pipe destinations.
 
  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
 
    for (var i = 0; i < len; i++)
      dests[i].emit('unpipe', this);
    return this;
  }
 
  // try to find the right one.
  var i = indexOf(state.pipes, dest);
  if (i === -1)
    return this;
 
  state.pipes.splice(i, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1)
    state.pipes = state.pipes[0];
 
  dest.emit('unpipe', this);
 
  return this;
};
 
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);
 
  // If listening to data, and it has not explicitly been paused,
  // then call resume to start the flow of data on the next tick.
  if (ev === 'data' && false !== this._readableState.flowing) {
    this.resume();
  }
 
  if (ev === 'readable' && this.readable) {
    var state = this._readableState;
    if (!state.readableListening) {
      state.readableListening = true;
      state.emittedReadable = false;
      state.needReadable = true;
      if (!state.reading) {
        var self = this;
        process.nextTick(function() {
          debug('readable nexttick read 0');
          self.read(0);
        });
      } else if (state.length) {
        emitReadable(this, state);
      }
    }
  }
 
  return res;
};
Readable.prototype.addListener = Readable.prototype.on;
 
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    state.flowing = true;
    if (!state.reading) {
      debug('resume read 0');
      this.read(0);
    }
    resume(this, state);
  }
  return this;
};
 
function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    process.nextTick(function() {
      resume_(stream, state);
    });
  }
}
 
function resume_(stream, state) {
  state.resumeScheduled = false;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading)
    stream.read(0);
}
 
Readable.prototype.pause = function() {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (false !== this._readableState.flowing) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  return this;
};
 
function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  if (state.flowing) {
    do {
      var chunk = stream.read();
    } while (null !== chunk && state.flowing);
  }
}
 
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
  var state = this._readableState;
  var paused = false;
 
  var self = this;
  stream.on('end', function() {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length)
        self.push(chunk);
    }
 
    self.push(null);
  });
 
  stream.on('data', function(chunk) {
    debug('wrapped data');
    if (state.decoder)
      chunk = state.decoder.write(chunk);
    if (!chunk || !state.objectMode && !chunk.length)
      return;
 
    var ret = self.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });
 
  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
      this[i] = function(method) { return function() {
        return stream[method].apply(stream, arguments);
      }}(i);
    }
  }
 
  // proxy certain important events.
  var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  forEach(events, function(ev) {
    stream.on(ev, self.emit.bind(self, ev));
  });
 
  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  self._read = function(n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };
 
  return self;
};
 
 
 
// exposed for testing purposes only.
Readable._fromList = fromList;
 
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
  var list = state.buffer;
  var length = state.length;
  var stringMode = !!state.decoder;
  var objectMode = !!state.objectMode;
  var ret;
 
  // nothing in the list, definitely empty.
  if (list.length === 0)
    return null;
 
  if (length === 0)
    ret = null;
  else if (objectMode)
    ret = list.shift();
  else if (!n || n >= length) {
    // read it all, truncate the array.
    if (stringMode)
      ret = list.join('');
    else
      ret = Buffer.concat(list, length);
    list.length = 0;
  } else {
    // read just some of it.
    if (n < list[0].length) {
      // just take a part of the first list item.
      // slice is the same for buffers and strings.
      var buf = list[0];
      ret = buf.slice(0, n);
      list[0] = buf.slice(n);
    } else if (n === list[0].length) {
      // first list is a perfect match
      ret = list.shift();
    } else {
      // complex case.
      // we have enough to cover it, but it spans past the first buffer.
      if (stringMode)
        ret = '';
      else
        ret = new Buffer(n);
 
      var c = 0;
      for (var i = 0, l = list.length; i < l && c < n; i++) {
        var buf = list[0];
        var cpy = Math.min(n - c, buf.length);
 
        if (stringMode)
          ret += buf.slice(0, cpy);
        else
          buf.copy(ret, c, 0, cpy);
 
        if (cpy < buf.length)
          list[0] = buf.slice(cpy);
        else
          list.shift();
 
        c += cpy;
      }
    }
  }
 
  return ret;
}
 
function endReadable(stream) {
  var state = stream._readableState;
 
  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0)
    throw new Error('endReadable called on non-empty stream');
 
  if (!state.endEmitted) {
    state.ended = true;
    process.nextTick(function() {
      // Check that we didn't get one last unshift.
      if (!state.endEmitted && state.length === 0) {
        state.endEmitted = true;
        stream.readable = false;
        stream.emit('end');
      }
    });
  }
}
 
function forEach (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
function indexOf (xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_transform.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_transform.js

Statements: 18.31% (13 / 71)      Branches: 0% (0 / 32)      Functions: 0% (0 / 11)      Lines: 18.31% (13 / 71)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                                                                                                                                1   1     1 1     1     1                     1                                                   1                                                         1                             1       1                                 1                           1                                    
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 
// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
 
module.exports = Transform;
 
var Duplex = require('./_stream_duplex');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
util.inherits(Transform, Duplex);
 
 
function TransformState(options, stream) {
  this.afterTransform = function(er, data) {
    return afterTransform(stream, er, data);
  };
 
  this.needTransform = false;
  this.transforming = false;
  this.writecb = null;
  this.writechunk = null;
}
 
function afterTransform(stream, er, data) {
  var ts = stream._transformState;
  ts.transforming = false;
 
  var cb = ts.writecb;
 
  if (!cb)
    return stream.emit('error', new Error('no writecb in Transform class'));
 
  ts.writechunk = null;
  ts.writecb = null;
 
  if (!util.isNullOrUndefined(data))
    stream.push(data);
 
  if (cb)
    cb(er);
 
  var rs = stream._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    stream._read(rs.highWaterMark);
  }
}
 
 
function Transform(options) {
  if (!(this instanceof Transform))
    return new Transform(options);
 
  Duplex.call(this, options);
 
  this._transformState = new TransformState(options, this);
 
  // when the writable side finishes, then flush out anything remaining.
  var stream = this;
 
  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;
 
  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;
 
  this.once('prefinish', function() {
    if (util.isFunction(this._flush))
      this._flush(function(er) {
        done(stream, er);
      });
    else
      done(stream);
  });
}
 
Transform.prototype.push = function(chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};
 
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
  throw new Error('not implemented');
};
 
Transform.prototype._write = function(chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform ||
        rs.needReadable ||
        rs.length < rs.highWaterMark)
      this._read(rs.highWaterMark);
  }
};
 
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
  var ts = this._transformState;
 
  if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};
 
 
function done(stream, er) {
  if (er)
    return stream.emit('error', er);
 
  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  var ws = stream._writableState;
  var ts = stream._transformState;
 
  if (ws.length)
    throw new Error('calling transform done when ws.length != 0');
 
  if (ts.transforming)
    throw new Error('calling transform done when still transforming');
 
  return stream.push(null);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_writable.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/lib/_stream_writable.js

Statements: 14.35% (32 / 223)      Branches: 0% (0 / 116)      Functions: 0% (0 / 31)      Lines: 14.35% (32 / 223)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479                                                  1     1     1       1 1     1   1   1           1                                                                                                                                                                               1                                 1         1                           1                               1                                                     1           1                             1                       1                                         1                       1                             1             1                                                           1                     1                 1                                                                                                     1         1   1                                                     1             1             1                         1                        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
 
module.exports = Writable;
 
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
 
Writable.WritableState = WritableState;
 
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var Stream = require('stream');
 
util.inherits(Writable, Stream);
 
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
}
 
function WritableState(options, stream) {
  var Duplex = require('./_stream_duplex');
 
  options = options || {};
 
  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  var defaultHwm = options.objectMode ? 16 : 16 * 1024;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
 
  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;
 
  if (stream instanceof Duplex)
    this.objectMode = this.objectMode || !!options.writableObjectMode;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;
 
  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;
 
  // a flag to see when we're in the middle of a write.
  this.writing = false;
 
  // when true all writes will be buffered until .uncork() call
  this.corked = 0;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;
 
  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function(er) {
    onwrite(stream, er);
  };
 
  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;
 
  // the amount that is being written when _write is called.
  this.writelen = 0;
 
  this.buffer = [];
 
  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;
 
  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;
 
  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;
}
 
function Writable(options) {
  var Duplex = require('./_stream_duplex');
 
  // Writable ctor is applied to Duplexes, though they're not
  // instanceof Writable, they're instanceof Readable.
  if (!(this instanceof Writable) && !(this instanceof Duplex))
    return new Writable(options);
 
  this._writableState = new WritableState(options, this);
 
  // legacy.
  this.writable = true;
 
  Stream.call(this);
}
 
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
  this.emit('error', new Error('Cannot pipe. Not readable.'));
};
 
 
function writeAfterEnd(stream, state, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  process.nextTick(function() {
    cb(er);
  });
}
 
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  if (!util.isBuffer(chunk) &&
      !util.isString(chunk) &&
      !util.isNullOrUndefined(chunk) &&
      !state.objectMode) {
    var er = new TypeError('Invalid non-string/buffer chunk');
    stream.emit('error', er);
    process.nextTick(function() {
      cb(er);
    });
    valid = false;
  }
  return valid;
}
 
Writable.prototype.write = function(chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
 
  if (util.isFunction(encoding)) {
    cb = encoding;
    encoding = null;
  }
 
  if (util.isBuffer(chunk))
    encoding = 'buffer';
  else if (!encoding)
    encoding = state.defaultEncoding;
 
  if (!util.isFunction(cb))
    cb = function() {};
 
  if (state.ended)
    writeAfterEnd(this, state, cb);
  else if (validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, chunk, encoding, cb);
  }
 
  return ret;
};
 
Writable.prototype.cork = function() {
  var state = this._writableState;
 
  state.corked++;
};
 
Writable.prototype.uncork = function() {
  var state = this._writableState;
 
  if (state.corked) {
    state.corked--;
 
    if (!state.writing &&
        !state.corked &&
        !state.finished &&
        !state.bufferProcessing &&
        state.buffer.length)
      clearBuffer(this, state);
  }
};
 
function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode &&
      state.decodeStrings !== false &&
      util.isString(chunk)) {
    chunk = new Buffer(chunk, encoding);
  }
  return chunk;
}
 
// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
  chunk = decodeChunk(state, chunk, encoding);
  if (util.isBuffer(chunk))
    encoding = 'buffer';
  var len = state.objectMode ? 1 : chunk.length;
 
  state.length += len;
 
  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret)
    state.needDrain = true;
 
  if (state.writing || state.corked)
    state.buffer.push(new WriteReq(chunk, encoding, cb));
  else
    doWrite(stream, state, false, len, chunk, encoding, cb);
 
  return ret;
}
 
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (writev)
    stream._writev(chunk, state.onwrite);
  else
    stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}
 
function onwriteError(stream, state, sync, er, cb) {
  if (sync)
    process.nextTick(function() {
      state.pendingcb--;
      cb(er);
    });
  else {
    state.pendingcb--;
    cb(er);
  }
 
  stream._writableState.errorEmitted = true;
  stream.emit('error', er);
}
 
function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}
 
function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;
 
  onwriteStateUpdate(state);
 
  if (er)
    onwriteError(stream, state, sync, er, cb);
  else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(stream, state);
 
    if (!finished &&
        !state.corked &&
        !state.bufferProcessing &&
        state.buffer.length) {
      clearBuffer(stream, state);
    }
 
    if (sync) {
      process.nextTick(function() {
        afterWrite(stream, state, finished, cb);
      });
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}
 
function afterWrite(stream, state, finished, cb) {
  if (!finished)
    onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}
 
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}
 
 
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
 
  if (stream._writev && state.buffer.length > 1) {
    // Fast case, write everything using _writev()
    var cbs = [];
    for (var c = 0; c < state.buffer.length; c++)
      cbs.push(state.buffer[c].callback);
 
    // count the one we are adding, as well.
    // TODO(isaacs) clean this up
    state.pendingcb++;
    doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
      for (var i = 0; i < cbs.length; i++) {
        state.pendingcb--;
        cbs[i](err);
      }
    });
 
    // Clear buffer
    state.buffer = [];
  } else {
    // Slow case, write chunks one-by-one
    for (var c = 0; c < state.buffer.length; c++) {
      var entry = state.buffer[c];
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;
 
      doWrite(stream, state, false, len, chunk, encoding, cb);
 
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        c++;
        break;
      }
    }
 
    if (c < state.buffer.length)
      state.buffer = state.buffer.slice(c);
    else
      state.buffer.length = 0;
  }
 
  state.bufferProcessing = false;
}
 
Writable.prototype._write = function(chunk, encoding, cb) {
  cb(new Error('not implemented'));
 
};
 
Writable.prototype._writev = null;
 
Writable.prototype.end = function(chunk, encoding, cb) {
  var state = this._writableState;
 
  if (util.isFunction(chunk)) {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (util.isFunction(encoding)) {
    cb = encoding;
    encoding = null;
  }
 
  if (!util.isNullOrUndefined(chunk))
    this.write(chunk, encoding);
 
  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }
 
  // ignore unnecessary end() calls.
  if (!state.ending && !state.finished)
    endWritable(this, state, cb);
};
 
 
function needFinish(stream, state) {
  return (state.ending &&
          state.length === 0 &&
          !state.finished &&
          !state.writing);
}
 
function prefinish(stream, state) {
  if (!state.prefinished) {
    state.prefinished = true;
    stream.emit('prefinish');
  }
}
 
function finishMaybe(stream, state) {
  var need = needFinish(stream, state);
  if (need) {
    if (state.pendingcb === 0) {
      prefinish(stream, state);
      state.finished = true;
      stream.emit('finish');
    } else
      prefinish(stream, state);
  }
  return need;
}
 
function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished)
      process.nextTick(cb);
    else
      stream.once('finish', cb);
  }
  state.ended = true;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/core-util-is/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/core-util-is/lib/

Statements: 63.83% (30 / 47)      Branches: 0% (0 / 12)      Functions: 0% (0 / 15)      Lines: 63.83% (30 / 47)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/core-util-is/lib/
File Statements Branches Functions Lines
util.js 63.83% (30 / 47) 0% (0 / 12) 0% (0 / 15) 63.83% (30 / 47)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

Statements: 63.83% (30 / 47)      Branches: 0% (0 / 12)      Functions: 0% (0 / 15)      Lines: 63.83% (30 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109                                                1           1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1               1   1   1        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
 
function isArray(arg) {
  if (Array.isArray) {
    return Array.isArray(arg);
  }
  return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
 
function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
 
function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;
 
function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
 
function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;
 
function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;
 
function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
 
function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;
 
function isRegExp(re) {
  return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
 
function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
 
function isDate(d) {
  return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
 
function isError(e) {
  return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
 
function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;
 
function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
 
exports.isBuffer = Buffer.isBuffer;
 
function objectToString(o) {
  return Object.prototype.toString.call(o);
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/
File Statements Branches Functions Lines
index.js 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/index.js

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

1 2 3 4 51        
module.exports = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/stream-iterate/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/stream-iterate/

Statements: 5.36% (3 / 56)      Branches: 0% (0 / 24)      Functions: 0% (0 / 9)      Lines: 6.52% (3 / 46)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/stream-iterate/
File Statements Branches Functions Lines
index.js 5.36% (3 / 56) 0% (0 / 24) 0% (0 / 9) 6.52% (3 / 46)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/stream-iterate/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/sorted-union-stream/node_modules/stream-iterate/index.js

Statements: 5.36% (3 / 56)      Branches: 0% (0 / 24)      Functions: 0% (0 / 9)      Lines: 6.52% (3 / 46)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 711   1         1                                                                                                                              
var Readable = require('stream').Readable
 
var stream2 = function (stream) {
  if (stream._readableState) return stream
  return new Readable({objectMode: true, highWaterMark: 16}).wrap(stream)
}
 
module.exports = function (stream) {
  stream = stream2(stream)
 
  var ended = false
  var data = null
  var err = null
  var destroyed = false
  var fn = null
 
  var consume = function (e) {
    if (e) {
      destroyed = true
      if (stream.destroy) stream.destroy(e)
      return
    }
 
    data = null
    err = null
  }
 
  var onresult = function () {
    if (!fn) return
    var tmp = fn
    fn = undefined
    tmp(err, data, consume)
  }
 
  var update = function () {
    if (!fn) return
    data = stream.read()
    if (data === null && !ended) return
    onresult()
  }
 
  var onend = function () {
    ended = true
    onresult()
  }
 
  stream.on('readable', update)
 
  stream.on('error', function (e) {
    err = e
    onresult()
  })
 
  stream.on('close', function () {
    if (stream._readableState.ended) return
    onend()
  })
 
  stream.on('end', onend)
 
  return function (callback) {
    if (destroyed) return
    if (err) return callback(err, null, consume)
    if (data) return callback(null, data, consume)
    if (ended) return callback(null, null, consume)
    fn = callback
    update()
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/strip-ansi/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/strip-ansi/

Statements: 66.67% (2 / 3)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/strip-ansi/
File Statements Branches Functions Lines
index.js 66.67% (2 / 3) 0% (0 / 2) 0% (0 / 1) 66.67% (2 / 3)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/strip-ansi/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/strip-ansi/index.js

Statements: 66.67% (2 / 3)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 6 7 8  1   1        
'use strict';
var ansiRegex = require('ansi-regex')();
 
module.exports = function (str) {
	return typeof str === 'string' ? str.replace(ansiRegex, '') : str;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/

Statements: 100% (48 / 48)      Branches: 100% (6 / 6)      Functions: 100% (3 / 3)      Lines: 100% (47 / 47)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/tar/
File Statements Branches Functions Lines
tar.js 100% (48 / 48) 100% (6 / 6) 100% (3 / 3) 100% (47 / 47)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/tar.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/tar.js

Statements: 100% (48 / 48)      Branches: 100% (6 / 6)      Functions: 100% (3 / 3)      Lines: 100% (47 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175    1                             1 1 1 1 1 1 1 1 1         1                   1   1 1 1 1 1 1 1 1                   1     1 17 17       1 18         1                                                     1 22       1                               1                               1 13     1                                 1 1 1 1 1 1 1 1 1 1   1 1 1    
// field paths that every tar file must have.
// header is padded to 512 bytes.
var f = 0
  , fields = {}
  , path = fields.path = f++
  , mode = fields.mode = f++
  , uid = fields.uid = f++
  , gid = fields.gid = f++
  , size = fields.size = f++
  , mtime = fields.mtime = f++
  , cksum = fields.cksum = f++
  , type = fields.type = f++
  , linkpath = fields.linkpath = f++
  , headerSize = 512
  , blockSize = 512
  , fieldSize = []
 
fieldSize[path] = 100
fieldSize[mode] = 8
fieldSize[uid] = 8
fieldSize[gid] = 8
fieldSize[size] = 12
fieldSize[mtime] = 12
fieldSize[cksum] = 8
fieldSize[type] = 1
fieldSize[linkpath] = 100
 
// "ustar\0" may introduce another bunch of headers.
// these are optional, and will be nulled out if not present.
 
var ustar = fields.ustar = f++
  , ustarver = fields.ustarver = f++
  , uname = fields.uname = f++
  , gname = fields.gname = f++
  , devmaj = fields.devmaj = f++
  , devmin = fields.devmin = f++
  , prefix = fields.prefix = f++
  , fill = fields.fill = f++
 
// terminate fields.
fields[f] = null
 
fieldSize[ustar] = 6
fieldSize[ustarver] = 2
fieldSize[uname] = 32
fieldSize[gname] = 32
fieldSize[devmaj] = 8
fieldSize[devmin] = 8
fieldSize[prefix] = 155
fieldSize[fill] = 12
 
// nb: prefix field may in fact be 130 bytes of prefix,
// a null char, 12 bytes for atime, 12 bytes for ctime.
//
// To recognize this format:
// 1. prefix[130] === ' ' or '\0'
// 2. atime and ctime are octal numeric values
// 3. atime and ctime have ' ' in their last byte
 
var fieldEnds = {}
  , fieldOffs = {}
  , fe = 0
for (var i = 0; i < f; i ++) {
  fieldOffs[i] = fe
  fieldEnds[i] = (fe += fieldSize[i])
}
 
// build a translation table of field paths.
Object.keys(fields).forEach(function (f) {
  if (fields[f] !== null) fields[fields[f]] = f
})
 
// different values of the 'type' field
// paths match the values of Stats.isX() functions, where appropriate
var types =
  { 0: "File"
  , "\0": "OldFile" // like 0
  , "": "OldFile"
  , 1: "Link"
  , 2: "SymbolicLink"
  , 3: "CharacterDevice"
  , 4: "BlockDevice"
  , 5: "Directory"
  , 6: "FIFO"
  , 7: "ContiguousFile" // like 0
  // posix headers
  , g: "GlobalExtendedHeader" // k=v for the rest of the archive
  , x: "ExtendedHeader" // k=v for the next file
  // vendor-specific stuff
  , A: "SolarisACL" // skip
  , D: "GNUDumpDir" // like 5, but with data, which should be skipped
  , I: "Inode" // metadata only, skip
  , K: "NextFileHasLongLinkpath" // data = link path of next file
  , L: "NextFileHasLongPath" // data = path of next file
  , M: "ContinuationFile" // skip
  , N: "OldGnuLongPath" // like L
  , S: "SparseFile" // skip
  , V: "TapeVolumeHeader" // skip
  , X: "OldExtendedHeader" // like x
  }
 
Object.keys(types).forEach(function (t) {
  types[types[t]] = types[types[t]] || t
})
 
// values for the mode field
var modes =
  { suid: 04000 // set uid on extraction
  , sgid: 02000 // set gid on extraction
  , svtx: 01000 // set restricted deletion flag on dirs on extraction
  , uread:  0400
  , uwrite: 0200
  , uexec:  0100
  , gread:  040
  , gwrite: 020
  , gexec:  010
  , oread:  4
  , owrite: 2
  , oexec:  1
  , all: 07777
  }
 
var numeric =
  { mode: true
  , uid: true
  , gid: true
  , size: true
  , mtime: true
  , devmaj: true
  , devmin: true
  , cksum: true
  , atime: true
  , ctime: true
  , dev: true
  , ino: true
  , nlink: true
  }
 
Object.keys(modes).forEach(function (t) {
  modes[modes[t]] = modes[modes[t]] || t
})
 
var knownExtended =
  { atime: true
  , charset: true
  , comment: true
  , ctime: true
  , gid: true
  , gname: true
  , linkpath: true
  , mtime: true
  , path: true
  , realtime: true
  , security: true
  , size: true
  , uid: true
  , uname: true }
 
 
exports.fields = fields
exports.fieldSize = fieldSize
exports.fieldOffs = fieldOffs
exports.fieldEnds = fieldEnds
exports.types = types
exports.modes = modes
exports.numeric = numeric
exports.headerSize = headerSize
exports.blockSize = blockSize
exports.knownExtended = knownExtended
 
exports.Pack = require("./lib/pack.js")
exports.Parse = require("./lib/parse.js")
exports.Extract = require("./lib/extract.js")
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/

Statements: 11.9% (102 / 857)      Branches: 0.21% (1 / 467)      Functions: 1.01% (1 / 99)      Lines: 12.66% (101 / 798)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/tar/lib/
File Statements Branches Functions Lines
buffer-entry.js 35.71% (5 / 14) 100% (0 / 0) 0% (0 / 3) 35.71% (5 / 14)
entry-writer.js 13.19% (12 / 91) 0% (0 / 34) 0% (0 / 15) 14.12% (12 / 85)
entry.js 11.71% (13 / 111) 0% (0 / 52) 0% (0 / 13) 12.26% (13 / 106)
extended-header-writer.js 12% (9 / 75) 0% (0 / 72) 0% (0 / 8) 13.43% (9 / 67)
extended-header.js 17.39% (12 / 69) 0% (0 / 26) 25% (1 / 4) 17.91% (12 / 67)
extract.js 10% (5 / 50) 0% (0 / 26) 0% (0 / 7) 10.64% (5 / 47)
global-header-writer.js 50% (4 / 8) 0% (0 / 2) 0% (0 / 1) 50% (4 / 8)
header.js 9.34% (17 / 182) 0.77% (1 / 130) 0% (0 / 10) 10.3% (17 / 165)
pack.js 11.54% (15 / 130) 0% (0 / 62) 0% (0 / 19) 11.86% (14 / 118)
parse.js 7.87% (10 / 127) 0% (0 / 63) 0% (0 / 19) 8.26% (10 / 121)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/buffer-entry.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/buffer-entry.js

Statements: 35.71% (5 / 14)      Branches: 100% (0 / 0)      Functions: 0% (0 / 3)      Lines: 35.71% (5 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32              1   1     1                   1     1            
// just like the Entry class, but it buffers the contents
//
// XXX It would be good to set a maximum BufferEntry filesize,
// since it eats up memory.  In normal operation,
// these are only for long filenames or link names, which are
// rarely very big.
 
module.exports = BufferEntry
 
var inherits = require("inherits")
  , Entry = require("./entry.js")
 
function BufferEntry () {
  Entry.apply(this, arguments)
  this._buffer = new Buffer(this.props.size)
  this._offset = 0
  this.body = ""
  this.on("end", function () {
    this.body = this._buffer.toString().slice(0, -1)
  })
}
 
inherits(BufferEntry, Entry)
 
// collect the bytes as they come in.
BufferEntry.prototype.write = function (c) {
  c.copy(this._buffer, this._offset)
  this._offset += c.length
  Entry.prototype.write.call(this, c)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/entry-writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/entry-writer.js

Statements: 13.19% (12 / 91)      Branches: 0% (0 / 34)      Functions: 0% (0 / 15)      Lines: 14.12% (12 / 85)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 1711   1                 1   1                                                                                       1                 1                 1           1             1                     1                                                       1                                                                                 1    
module.exports = EntryWriter
 
var tar = require("../tar.js")
  , TarHeader = require("./header.js")
  , Entry = require("./entry.js")
  , inherits = require("inherits")
  , BlockStream = require("block-stream")
  , ExtendedHeaderWriter
  , Stream = require("stream").Stream
  , EOF = {}
 
inherits(EntryWriter, Stream)
 
function EntryWriter (props) {
  var me = this
 
  if (!(me instanceof EntryWriter)) {
    return new EntryWriter(props)
  }
 
  Stream.apply(this)
 
  me.writable = true
  me.readable = true
 
  me._stream = new BlockStream(512)
 
  me._stream.on("data", function (c) {
    me.emit("data", c)
  })
 
  me._stream.on("drain", function () {
    me.emit("drain")
  })
 
  me._stream.on("end", function () {
    me.emit("end")
    me.emit("close")
  })
 
  me.props = props
  if (props.type === "Directory") {
    props.size = 0
  }
  props.ustar = "ustar\0"
  props.ustarver = "00"
  me.path = props.path
 
  me._buffer = []
  me._didHeader = false
  me._meta = false
 
  me.on("pipe", function () {
    me._process()
  })
}
 
EntryWriter.prototype.write = function (c) {
  // console.error(".. ew write")
  if (this._ended) return this.emit("error", new Error("write after end"))
  this._buffer.push(c)
  this._process()
  this._needDrain = this._buffer.length > 0
  return !this._needDrain
}
 
EntryWriter.prototype.end = function (c) {
  // console.error(".. ew end")
  if (c) this._buffer.push(c)
  this._buffer.push(EOF)
  this._ended = true
  this._process()
  this._needDrain = this._buffer.length > 0
}
 
EntryWriter.prototype.pause = function () {
  // console.error(".. ew pause")
  this._paused = true
  this.emit("pause")
}
 
EntryWriter.prototype.resume = function () {
  // console.error(".. ew resume")
  this._paused = false
  this.emit("resume")
  this._process()
}
 
EntryWriter.prototype.add = function (entry) {
  // console.error(".. ew add")
  if (!this.parent) return this.emit("error", new Error("no parent"))
 
  // make sure that the _header and such is emitted, and clear out
  // the _currentEntry link on the parent.
  if (!this._ended) this.end()
 
  return this.parent.add(entry)
}
 
EntryWriter.prototype._header = function () {
  // console.error(".. ew header")
  if (this._didHeader) return
  this._didHeader = true
 
  var headerBlock = TarHeader.encode(this.props)
 
  if (this.props.needExtended && !this._meta) {
    var me = this
 
    ExtendedHeaderWriter = ExtendedHeaderWriter ||
      require("./extended-header-writer.js")
 
    ExtendedHeaderWriter(this.props)
      .on("data", function (c) {
        me.emit("data", c)
      })
      .on("error", function (er) {
        me.emit("error", er)
      })
      .end()
  }
 
  // console.error(".. .. ew headerBlock emitting")
  this.emit("data", headerBlock)
  this.emit("header")
}
 
EntryWriter.prototype._process = function () {
  // console.error(".. .. ew process")
  if (!this._didHeader && !this._meta) {
    this._header()
  }
 
  if (this._paused || this._processing) {
    // console.error(".. .. .. paused=%j, processing=%j", this._paused, this._processing)
    return
  }
 
  this._processing = true
 
  var buf = this._buffer
  for (var i = 0; i < buf.length; i ++) {
    // console.error(".. .. .. i=%d", i)
 
    var c = buf[i]
 
    if (c === EOF) this._stream.end()
    else this._stream.write(c)
 
    if (this._paused) {
      // console.error(".. .. .. paused mid-emission")
      this._processing = false
      if (i < buf.length) {
        this._needDrain = true
        this._buffer = buf.slice(i + 1)
      }
      return
    }
  }
 
  // console.error(".. .. .. emitted")
  this._buffer.length = 0
  this._processing = false
 
  // console.error(".. .. .. emitting drain")
  this.emit("drain")
}
 
EntryWriter.prototype.destroy = function () {}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/entry.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/entry.js

Statements: 11.71% (13 / 111)      Branches: 0% (0 / 52)      Functions: 0% (0 / 13)      Lines: 12.26% (13 / 106)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222            1   1             1                                                                 1   1                                                         1           1         1                 1                                                                                 1                                                                                                                                                   1       1 1    
// A passthrough read/write stream that sets its properties
// based on a header, extendedHeader, and globalHeader
//
// Can be either a file system object of some sort, or
// a pax/ustar metadata entry.
 
module.exports = Entry
 
var TarHeader = require("./header.js")
  , tar = require("../tar")
  , assert = require("assert").ok
  , Stream = require("stream").Stream
  , inherits = require("inherits")
  , fstream = require("fstream").Abstract
 
function Entry (header, extended, global) {
  Stream.call(this)
  this.readable = true
  this.writable = true
 
  this._needDrain = false
  this._paused = false
  this._reading = false
  this._ending = false
  this._ended = false
  this._remaining = 0
  this._abort = false
  this._queue = []
  this._index = 0
  this._queueLen = 0
 
  this._read = this._read.bind(this)
 
  this.props = {}
  this._header = header
  this._extended = extended || {}
 
  // globals can change throughout the course of
  // a file parse operation.  Freeze it at its current state.
  this._global = {}
  var me = this
  Object.keys(global || {}).forEach(function (g) {
    me._global[g] = global[g]
  })
 
  this._setProps()
}
 
inherits(Entry, Stream)
 
Entry.prototype.write = function (c) {
  if (this._ending) this.error("write() after end()", null, true)
  if (this._remaining === 0) {
    this.error("invalid bytes past eof")
  }
 
  // often we'll get a bunch of \0 at the end of the last write,
  // since chunks will always be 512 bytes when reading a tarball.
  if (c.length > this._remaining) {
    c = c.slice(0, this._remaining)
  }
  this._remaining -= c.length
 
  // put it on the stack.
  var ql = this._queueLen
  this._queue.push(c)
  this._queueLen ++
 
  this._read()
 
  // either paused, or buffered
  if (this._paused || ql > 0) {
    this._needDrain = true
    return false
  }
 
  return true
}
 
Entry.prototype.end = function (c) {
  if (c) this.write(c)
  this._ending = true
  this._read()
}
 
Entry.prototype.pause = function () {
  this._paused = true
  this.emit("pause")
}
 
Entry.prototype.resume = function () {
  // console.error("    Tar Entry resume", this.path)
  this.emit("resume")
  this._paused = false
  this._read()
  return this._queueLen - this._index > 1
}
 
  // This is bound to the instance
Entry.prototype._read = function () {
  // console.error("    Tar Entry _read", this.path)
 
  if (this._paused || this._reading || this._ended) return
 
  // set this flag so that event handlers don't inadvertently
  // get multiple _read() calls running.
  this._reading = true
 
  // have any data to emit?
  while (this._index < this._queueLen && !this._paused) {
    var chunk = this._queue[this._index ++]
    this.emit("data", chunk)
  }
 
  // check if we're drained
  if (this._index >= this._queueLen) {
    this._queue.length = this._queueLen = this._index = 0
    if (this._needDrain) {
      this._needDrain = false
      this.emit("drain")
    }
    if (this._ending) {
      this._ended = true
      this.emit("end")
    }
  }
 
  // if the queue gets too big, then pluck off whatever we can.
  // this should be fairly rare.
  var mql = this._maxQueueLen
  if (this._queueLen > mql && this._index > 0) {
    mql = Math.min(this._index, mql)
    this._index -= mql
    this._queueLen -= mql
    this._queue = this._queue.slice(mql)
  }
 
  this._reading = false
}
 
Entry.prototype._setProps = function () {
  // props = extended->global->header->{}
  var header = this._header
    , extended = this._extended
    , global = this._global
    , props = this.props
 
  // first get the values from the normal header.
  var fields = tar.fields
  for (var f = 0; fields[f] !== null; f ++) {
    var field = fields[f]
      , val = header[field]
    if (typeof val !== "undefined") props[field] = val
  }
 
  // next, the global header for this file.
  // numeric values, etc, will have already been parsed.
  ;[global, extended].forEach(function (p) {
    Object.keys(p).forEach(function (f) {
      if (typeof p[f] !== "undefined") props[f] = p[f]
    })
  })
 
  // no nulls allowed in path or linkpath
  ;["path", "linkpath"].forEach(function (p) {
    if (props.hasOwnProperty(p)) {
      props[p] = props[p].split("\0")[0]
    }
  })
 
 
  // set date fields to be a proper date
  ;["mtime", "ctime", "atime"].forEach(function (p) {
    if (props.hasOwnProperty(p)) {
      props[p] = new Date(props[p] * 1000)
    }
  })
 
  // set the type so that we know what kind of file to create
  var type
  switch (tar.types[props.type]) {
    case "OldFile":
    case "ContiguousFile":
      type = "File"
      break
 
    case "GNUDumpDir":
      type = "Directory"
      break
 
    case undefined:
      type = "Unknown"
      break
 
    case "Link":
    case "SymbolicLink":
    case "CharacterDevice":
    case "BlockDevice":
    case "Directory":
    case "FIFO":
    default:
      type = tar.types[props.type]
  }
 
  this.type = type
  this.path = props.path
  this.size = props.size
 
  // size is special, since it signals when the file needs to end.
  this._remaining = props.size
}
 
// the parser may not call write if _abort is true. 
// useful for skipping data from some files quickly.
Entry.prototype.abort = function(){
  this._abort = true
}
 
Entry.prototype.warn = fstream.warn
Entry.prototype.error = fstream.error
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/extended-header-writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/extended-header-writer.js

Statements: 12% (9 / 75)      Branches: 0% (0 / 72)      Functions: 0% (0 / 8)      Lines: 13.43% (9 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193  1   1     1   1             1                                                                       1                                                   1                           1                                                                                                         1                                                                                                
 
module.exports = ExtendedHeaderWriter
 
var inherits = require("inherits")
  , EntryWriter = require("./entry-writer.js")
 
inherits(ExtendedHeaderWriter, EntryWriter)
 
var tar = require("../tar.js")
  , path = require("path")
  , TarHeader = require("./header.js")
 
// props is the props of the thing we need to write an
// extended header for.
// Don't be shy with it.  Just encode everything.
function ExtendedHeaderWriter (props) {
  // console.error(">> ehw ctor")
  var me = this
 
  if (!(me instanceof ExtendedHeaderWriter)) {
    return new ExtendedHeaderWriter(props)
  }
 
  me.fields = props
 
  var p =
    { path : ("PaxHeader" + path.join("/", props.path || ""))
             .replace(/\\/g, "/").substr(0, 100)
    , mode : props.mode || 0666
    , uid : props.uid || 0
    , gid : props.gid || 0
    , size : 0 // will be set later
    , mtime : props.mtime || Date.now() / 1000
    , type : "x"
    , linkpath : ""
    , ustar : "ustar\0"
    , ustarver : "00"
    , uname : props.uname || ""
    , gname : props.gname || ""
    , devmaj : props.devmaj || 0
    , devmin : props.devmin || 0
    }
 
 
  EntryWriter.call(me, p)
  // console.error(">> ehw props", me.props)
  me.props = p
 
  me._meta = true
}
 
ExtendedHeaderWriter.prototype.end = function () {
  // console.error(">> ehw end")
  var me = this
 
  if (me._ended) return
  me._ended = true
 
  me._encodeFields()
 
  if (me.props.size === 0) {
    // nothing to write!
    me._ready = true
    me._stream.end()
    return
  }
 
  me._stream.write(TarHeader.encode(me.props))
  me.body.forEach(function (l) {
    me._stream.write(l)
  })
  me._ready = true
 
  // console.error(">> ehw _process calling end()", me.props)
  this._stream.end()
}
 
ExtendedHeaderWriter.prototype._encodeFields = function () {
  // console.error(">> ehw _encodeFields")
  this.body = []
  if (this.fields.prefix) {
    this.fields.path = this.fields.prefix + "/" + this.fields.path
    this.fields.prefix = ""
  }
  encodeFields(this.fields, "", this.body, this.fields.noProprietary)
  var me = this
  this.body.forEach(function (l) {
    me.props.size += l.length
  })
}
 
function encodeFields (fields, prefix, body, nop) {
  // console.error(">> >> ehw encodeFields")
  // "%d %s=%s\n", <length>, <keyword>, <value>
  // The length is a decimal number, and includes itself and the \n
  // Numeric values are decimal strings.
 
  Object.keys(fields).forEach(function (k) {
    var val = fields[k]
      , numeric = tar.numeric[k]
 
    if (prefix) k = prefix + "." + k
 
    // already including NODETAR.type, don't need File=true also
    if (k === fields.type && val === true) return
 
    switch (k) {
      // don't include anything that's always handled just fine
      // in the normal header, or only meaningful in the context
      // of nodetar
      case "mode":
      case "cksum":
      case "ustar":
      case "ustarver":
      case "prefix":
      case "basename":
      case "dirname":
      case "needExtended":
      case "block":
      case "filter":
        return
 
      case "rdev":
        if (val === 0) return
        break
 
      case "nlink":
      case "dev": // Truly a hero among men, Creator of Star!
      case "ino": // Speak his name with reverent awe!  It is:
        k = "SCHILY." + k
        break
 
      default: break
    }
 
    if (val && typeof val === "object" &&
        !Buffer.isBuffer(val)) encodeFields(val, k, body, nop)
    else if (val === null || val === undefined) return
    else body.push.apply(body, encodeField(k, val, nop))
  })
 
  return body
}
 
function encodeField (k, v, nop) {
  // lowercase keys must be valid, otherwise prefix with
  // "NODETAR."
  if (k.charAt(0) === k.charAt(0).toLowerCase()) {
    var m = k.split(".")[0]
    if (!tar.knownExtended[m]) k = "NODETAR." + k
  }
 
  // no proprietary
  if (nop && k.charAt(0) !== k.charAt(0).toLowerCase()) {
    return []
  }
 
  if (typeof val === "number") val = val.toString(10)
 
  var s = new Buffer(" " + k + "=" + v + "\n")
    , digits = Math.floor(Math.log(s.length) / Math.log(10)) + 1
 
  // console.error("1 s=%j digits=%j s.length=%d", s.toString(), digits, s.length)
 
  // if adding that many digits will make it go over that length,
  // then add one to it. For example, if the string is:
  // " foo=bar\n"
  // then that's 9 characters.  With the "9", that bumps the length
  // up to 10.  However, this is invalid:
  // "10 foo=bar\n"
  // but, since that's actually 11 characters, since 10 adds another
  // character to the length, and the length includes the number
  // itself.  In that case, just bump it up again.
  if (s.length + digits >= Math.pow(10, digits)) digits += 1
  // console.error("2 s=%j digits=%j s.length=%d", s.toString(), digits, s.length)
 
  var len = digits + s.length
  // console.error("3 s=%j digits=%j s.length=%d len=%d", s.toString(), digits, s.length, len)
  var lenBuf = new Buffer("" + len)
  if (lenBuf.length + s.length !== len) {
    throw new Error("Bad length calculation\n"+
                    "len="+len+"\n"+
                    "lenBuf="+JSON.stringify(lenBuf.toString())+"\n"+
                    "lenBuf.length="+lenBuf.length+"\n"+
                    "digits="+digits+"\n"+
                    "s="+JSON.stringify(s.toString())+"\n"+
                    "s.length="+s.length)
  }
 
  return [lenBuf, s]
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/extended-header.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/extended-header.js

Statements: 17.39% (12 / 69)      Branches: 0% (0 / 26)      Functions: 25% (1 / 4)      Lines: 17.91% (12 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142                1   1               1                           1 1   1             1 4     1     1                     1                                                                                                                                               1                  
// An Entry consisting of:
//
// "%d %s=%s\n", <length>, <keyword>, <value>
//
// The length is a decimal number, and includes itself and the \n
// \0 does not terminate anything.  Only the length terminates the string.
// Numeric values are decimal strings.
 
module.exports = ExtendedHeader
 
var Entry = require("./entry.js")
  , inherits = require("inherits")
  , tar = require("../tar.js")
  , numeric = tar.numeric
  , keyTrans = { "SCHILY.dev": "dev"
               , "SCHILY.ino": "ino"
               , "SCHILY.nlink": "nlink" }
 
function ExtendedHeader () {
  Entry.apply(this, arguments)
  this.on("data", this._parse)
  this.fields = {}
  this._position = 0
  this._fieldPos = 0
  this._state = SIZE
  this._sizeBuf = []
  this._keyBuf = []
  this._valBuf = []
  this._size = -1
  this._key = ""
}
 
inherits(ExtendedHeader, Entry)
ExtendedHeader.prototype._parse = parse
 
var s = 0
  , states = ExtendedHeader.states = {}
  , SIZE = states.SIZE = s++
  , KEY  = states.KEY  = s++
  , VAL  = states.VAL  = s++
  , ERR  = states.ERR  = s++
 
Object.keys(states).forEach(function (s) {
  states[states[s]] = states[s]
})
 
states[s] = null
 
// char code values for comparison
var _0 = "0".charCodeAt(0)
  , _9 = "9".charCodeAt(0)
  , point = ".".charCodeAt(0)
  , a = "a".charCodeAt(0)
  , Z = "Z".charCodeAt(0)
  , a = "a".charCodeAt(0)
  , z = "z".charCodeAt(0)
  , space = " ".charCodeAt(0)
  , eq = "=".charCodeAt(0)
  , cr = "\n".charCodeAt(0)
 
function parse (c) {
  if (this._state === ERR) return
 
  for ( var i = 0, l = c.length
      ; i < l
      ; this._position++, this._fieldPos++, i++) {
    // console.error("top of loop, size="+this._size)
 
    var b = c[i]
 
    if (this._size >= 0 && this._fieldPos > this._size) {
      error(this, "field exceeds length="+this._size)
      return
    }
 
    switch (this._state) {
      case ERR: return
 
      case SIZE:
        // console.error("parsing size, b=%d, rest=%j", b, c.slice(i).toString())
        if (b === space) {
          this._state = KEY
          // this._fieldPos = this._sizeBuf.length
          this._size = parseInt(new Buffer(this._sizeBuf).toString(), 10)
          this._sizeBuf.length = 0
          continue
        }
        if (b < _0 || b > _9) {
          error(this, "expected [" + _0 + ".." + _9 + "], got " + b)
          return
        }
        this._sizeBuf.push(b)
        continue
 
      case KEY:
        // can be any char except =, not > size.
        if (b === eq) {
          this._state = VAL
          this._key = new Buffer(this._keyBuf).toString()
          if (keyTrans[this._key]) this._key = keyTrans[this._key]
          this._keyBuf.length = 0
          continue
        }
        this._keyBuf.push(b)
        continue
 
      case VAL:
        // field must end with cr
        if (this._fieldPos === this._size - 1) {
          // console.error("finished with "+this._key)
          if (b !== cr) {
            error(this, "expected \\n at end of field")
            return
          }
          var val = new Buffer(this._valBuf).toString()
          if (numeric[this._key]) {
            val = parseFloat(val)
          }
          this.fields[this._key] = val
 
          this._valBuf.length = 0
          this._state = SIZE
          this._size = -1
          this._fieldPos = -1
          continue
        }
        this._valBuf.push(b)
        continue
    }
  }
}
 
function error (me, msg) {
  msg = "invalid header: " + msg
      + "\nposition=" + me._position
      + "\nfield position=" + me._fieldPos
 
  me.error(msg)
  me.state = ERR
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/extract.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/extract.js

Statements: 10% (5 / 50)      Branches: 0% (0 / 26)      Functions: 0% (0 / 7)      Lines: 10.64% (5 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96    1   1         1                                                                                                                                                         1   1              
// give it a tarball and a path, and it'll dump the contents
 
module.exports = Extract
 
var tar = require("../tar.js")
  , fstream = require("fstream")
  , inherits = require("inherits")
  , path = require("path")
 
function Extract (opts) {
  if (!(this instanceof Extract)) return new Extract(opts)
  tar.Parse.apply(this)
 
  if (typeof opts !== "object") {
    opts = { path: opts }
  }
 
  // better to drop in cwd? seems more standard.
  opts.path = opts.path || path.resolve("node-tar-extract")
  opts.type = "Directory"
  opts.Directory = true
 
  // similar to --strip or --strip-components
  opts.strip = +opts.strip
  if (!opts.strip || opts.strip <= 0) opts.strip = 0
 
  this._fst = fstream.Writer(opts)
 
  this.pause()
  var me = this
 
  // Hardlinks in tarballs are relative to the root
  // of the tarball.  So, they need to be resolved against
  // the target directory in order to be created properly.
  me.on("entry", function (entry) {
    // if there's a "strip" argument, then strip off that many
    // path components.
    if (opts.strip) {
      var p = entry.path.split("/").slice(opts.strip).join("/")
      entry.path = entry.props.path = p
      if (entry.linkpath) {
        var lp = entry.linkpath.split("/").slice(opts.strip).join("/")
        entry.linkpath = entry.props.linkpath = lp
      }
    }
    if (entry.type === "Link") {
      entry.linkpath = entry.props.linkpath =
        path.join(opts.path, path.join("/", entry.props.linkpath))
    }
 
    if (entry.type === "SymbolicLink") {
      var dn = path.dirname(entry.path) || ""
      var linkpath = entry.props.linkpath
      var target = path.resolve(opts.path, dn, linkpath)
      if (target.indexOf(opts.path) !== 0) {
        linkpath = path.join(opts.path, path.join("/", linkpath))
      }
      entry.linkpath = entry.props.linkpath = linkpath
    }
  })
 
  this._fst.on("ready", function () {
    me.pipe(me._fst, { end: false })
    me.resume()
  })
 
  this._fst.on('error', function(err) {
    me.emit('error', err)
  })
 
  this._fst.on('drain', function() {
    me.emit('drain')
  })
 
  // this._fst.on("end", function () {
  //   console.error("\nEEEE Extract End", me._fst.path)
  // })
 
  this._fst.on("close", function () {
    // console.error("\nEEEE Extract End", me._fst.path)
    me.emit("finish")
    me.emit("end")
    me.emit("close")
  })
}
 
inherits(Extract, tar.Parse)
 
Extract.prototype._streamEnd = function () {
  var me = this
  if (!me._ended || me._entry) me.error("unexpected eof")
  me._fst.end()
  // my .end() is coming later.
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/global-header-writer.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/global-header-writer.js

Statements: 50% (4 / 8)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 50% (4 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161   1     1   1                
module.exports = GlobalHeaderWriter
 
var ExtendedHeaderWriter = require("./extended-header-writer.js")
  , inherits = require("inherits")
 
inherits(GlobalHeaderWriter, ExtendedHeaderWriter)
 
function GlobalHeaderWriter (props) {
  if (!(this instanceof GlobalHeaderWriter)) {
    return new GlobalHeaderWriter(props)
  }
  ExtendedHeaderWriter.call(this, props)
  this.props.type = "g"
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/header.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/header.js

Statements: 9.34% (17 / 182)      Branches: 0.77% (1 / 130)      Functions: 0% (0 / 10)      Lines: 10.3% (17 / 165)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387        1   1                     1         1             1 1 1           1                                                                                                                                                                                                                                           1       1                                                                           1                                                                         1                             1                                                     1                   1                                                                                                                           1                                                       1                    
// parse a 512-byte header block to a data object, or vice-versa
// If the data won't fit nicely in a simple header, then generate
// the appropriate extended header file, and return that.
 
module.exports = TarHeader
 
var tar = require("../tar.js")
  , fields = tar.fields
  , fieldOffs = tar.fieldOffs
  , fieldEnds = tar.fieldEnds
  , fieldSize = tar.fieldSize
  , numeric = tar.numeric
  , assert = require("assert").ok
  , space = " ".charCodeAt(0)
  , slash = "/".charCodeAt(0)
  , bslash = process.platform === "win32" ? "\\".charCodeAt(0) : null
 
function TarHeader (block) {
  if (!(this instanceof TarHeader)) return new TarHeader(block)
  if (block) this.decode(block)
}
 
TarHeader.prototype =
  { decode : decode
  , encode: encode
  , calcSum: calcSum
  , checkSum: checkSum
  }
 
TarHeader.parseNumeric = parseNumeric
TarHeader.encode = encode
TarHeader.decode = decode
 
// note that this will only do the normal ustar header, not any kind
// of extended posix header file.  If something doesn't fit comfortably,
// then it will set obj.needExtended = true, and set the block to
// the closest approximation.
function encode (obj) {
  if (!obj && !(this instanceof TarHeader)) throw new Error(
    "encode must be called on a TarHeader, or supplied an object")
 
  obj = obj || this
  var block = obj.block = new Buffer(512)
 
  // if the object has a "prefix", then that's actually an extension of
  // the path field.
  if (obj.prefix) {
    // console.error("%% header encoding, got a prefix", obj.prefix)
    obj.path = obj.prefix + "/" + obj.path
    // console.error("%% header encoding, prefixed path", obj.path)
    obj.prefix = ""
  }
 
  obj.needExtended = false
 
  if (obj.mode) {
    if (typeof obj.mode === "string") obj.mode = parseInt(obj.mode, 8)
    obj.mode = obj.mode & 0777
  }
 
  for (var f = 0; fields[f] !== null; f ++) {
    var field = fields[f]
      , off = fieldOffs[f]
      , end = fieldEnds[f]
      , ret
 
    switch (field) {
      case "cksum":
        // special, done below, after all the others
        break
 
      case "prefix":
        // special, this is an extension of the "path" field.
        // console.error("%% header encoding, skip prefix later")
        break
 
      case "type":
        // convert from long name to a single char.
        var type = obj.type || "0"
        if (type.length > 1) {
          type = tar.types[obj.type]
          if (!type) type = "0"
        }
        writeText(block, off, end, type)
        break
 
      case "path":
        // uses the "prefix" field if > 100 bytes, but <= 255
        var pathLen = Buffer.byteLength(obj.path)
          , pathFSize = fieldSize[fields.path]
          , prefFSize = fieldSize[fields.prefix]
 
        // paths between 100 and 255 should use the prefix field.
        // longer than 255
        if (pathLen > pathFSize &&
            pathLen <= pathFSize + prefFSize) {
          // need to find a slash somewhere in the middle so that
          // path and prefix both fit in their respective fields
          var searchStart = pathLen - 1 - pathFSize
            , searchEnd = prefFSize
            , found = false
            , pathBuf = new Buffer(obj.path)
 
          for ( var s = searchStart
              ; (s <= searchEnd)
              ; s ++ ) {
            if (pathBuf[s] === slash || pathBuf[s] === bslash) {
              found = s
              break
            }
          }
 
          if (found !== false) {
            prefix = pathBuf.slice(0, found).toString("utf8")
            path = pathBuf.slice(found + 1).toString("utf8")
 
            ret = writeText(block, off, end, path)
            off = fieldOffs[fields.prefix]
            end = fieldEnds[fields.prefix]
            // console.error("%% header writing prefix", off, end, prefix)
            ret = writeText(block, off, end, prefix) || ret
            break
          }
        }
 
        // paths less than 100 chars don't need a prefix
        // and paths longer than 255 need an extended header and will fail
        // on old implementations no matter what we do here.
        // Null out the prefix, and fallthrough to default.
        // console.error("%% header writing no prefix")
        var poff = fieldOffs[fields.prefix]
          , pend = fieldEnds[fields.prefix]
        writeText(block, poff, pend, "")
        // fallthrough
 
      // all other fields are numeric or text
      default:
        ret = numeric[field]
            ? writeNumeric(block, off, end, obj[field])
            : writeText(block, off, end, obj[field] || "")
        break
    }
    obj.needExtended = obj.needExtended || ret
  }
 
  var off = fieldOffs[fields.cksum]
    , end = fieldEnds[fields.cksum]
 
  writeNumeric(block, off, end, calcSum.call(this, block))
 
  return block
}
 
// if it's a negative number, or greater than will fit,
// then use write256.
var MAXNUM = { 12: 077777777777
             , 11: 07777777777
             , 8 : 07777777
             , 7 : 0777777 }
function writeNumeric (block, off, end, num) {
  var writeLen = end - off
    , maxNum = MAXNUM[writeLen] || 0
 
  num = num || 0
  // console.error("  numeric", num)
 
  if (num instanceof Date ||
      Object.prototype.toString.call(num) === "[object Date]") {
    num = num.getTime() / 1000
  }
 
  if (num > maxNum || num < 0) {
    write256(block, off, end, num)
    // need an extended header if negative or too big.
    return true
  }
 
  // god, tar is so annoying
  // if the string is small enough, you should put a space
  // between the octal string and the \0, but if it doesn't
  // fit, then don't.
  var numStr = Math.floor(num).toString(8)
  if (num < MAXNUM[writeLen - 1]) numStr += " "
 
  // pad with "0" chars
  if (numStr.length < writeLen) {
    numStr = (new Array(writeLen - numStr.length).join("0")) + numStr
  }
 
  if (numStr.length !== writeLen - 1) {
    throw new Error("invalid length: " + JSON.stringify(numStr) + "\n" +
                    "expected: "+writeLen)
  }
  block.write(numStr, off, writeLen, "utf8")
  block[end - 1] = 0
}
 
function write256 (block, off, end, num) {
  var buf = block.slice(off, end)
  var positive = num >= 0
  buf[0] = positive ? 0x80 : 0xFF
 
  // get the number as a base-256 tuple
  if (!positive) num *= -1
  var tuple = []
  do {
    var n = num % 256
    tuple.push(n)
    num = (num - n) / 256
  } while (num)
 
  var bytes = tuple.length
 
  var fill = buf.length - bytes
  for (var i = 1; i < fill; i ++) {
    buf[i] = positive ? 0 : 0xFF
  }
 
  // tuple is a base256 number, with [0] as the *least* significant byte
  // if it's negative, then we need to flip all the bits once we hit the
  // first non-zero bit.  The 2's-complement is (0x100 - n), and the 1's-
  // complement is (0xFF - n).
  var zero = true
  for (i = bytes; i > 0; i --) {
    var byte = tuple[bytes - i]
    if (positive) buf[fill + i] = byte
    else if (zero && byte === 0) buf[fill + i] = 0
    else if (zero) {
      zero = false
      buf[fill + i] = 0x100 - byte
    } else buf[fill + i] = 0xFF - byte
  }
}
 
function writeText (block, off, end, str) {
  // strings are written as utf8, then padded with \0
  var strLen = Buffer.byteLength(str)
    , writeLen = Math.min(strLen, end - off)
    // non-ascii fields need extended headers
    // long fields get truncated
    , needExtended = strLen !== str.length || strLen > writeLen
 
  // write the string, and null-pad
  if (writeLen > 0) block.write(str, off, writeLen, "utf8")
  for (var i = off + writeLen; i < end; i ++) block[i] = 0
 
  return needExtended
}
 
function calcSum (block) {
  block = block || this.block
  assert(Buffer.isBuffer(block) && block.length === 512)
 
  if (!block) throw new Error("Need block to checksum")
 
  // now figure out what it would be if the cksum was "        "
  var sum = 0
    , start = fieldOffs[fields.cksum]
    , end = fieldEnds[fields.cksum]
 
  for (var i = 0; i < fieldOffs[fields.cksum]; i ++) {
    sum += block[i]
  }
 
  for (var i = start; i < end; i ++) {
    sum += space
  }
 
  for (var i = end; i < 512; i ++) {
    sum += block[i]
  }
 
  return sum
}
 
 
function checkSum (block) {
  var sum = calcSum.call(this, block)
  block = block || this.block
 
  var cksum = block.slice(fieldOffs[fields.cksum], fieldEnds[fields.cksum])
  cksum = parseNumeric(cksum)
 
  return cksum === sum
}
 
function decode (block) {
  block = block || this.block
  assert(Buffer.isBuffer(block) && block.length === 512)
 
  this.block = block
  this.cksumValid = this.checkSum()
 
  var prefix = null
 
  // slice off each field.
  for (var f = 0; fields[f] !== null; f ++) {
    var field = fields[f]
      , val = block.slice(fieldOffs[f], fieldEnds[f])
 
    switch (field) {
      case "ustar":
        // if not ustar, then everything after that is just padding.
        if (val.toString() !== "ustar\0") {
          this.ustar = false
          return
        } else {
          // console.error("ustar:", val, val.toString())
          this.ustar = val.toString()
        }
        break
 
      // prefix is special, since it might signal the xstar header
      case "prefix":
        var atime = parseNumeric(val.slice(131, 131 + 12))
          , ctime = parseNumeric(val.slice(131 + 12, 131 + 12 + 12))
        if ((val[130] === 0 || val[130] === space) &&
            typeof atime === "number" &&
            typeof ctime === "number" &&
            val[131 + 12] === space &&
            val[131 + 12 + 12] === space) {
          this.atime = atime
          this.ctime = ctime
          val = val.slice(0, 130)
        }
        prefix = val.toString("utf8").replace(/\0+$/, "")
        // console.error("%% header reading prefix", prefix)
        break
 
      // all other fields are null-padding text
      // or a number.
      default:
        if (numeric[field]) {
          this[field] = parseNumeric(val)
        } else {
          this[field] = val.toString("utf8").replace(/\0+$/, "")
        }
        break
    }
  }
 
  // if we got a prefix, then prepend it to the path.
  if (prefix) {
    this.path = prefix + "/" + this.path
    // console.error("%% header got a prefix", this.path)
  }
}
 
function parse256 (buf) {
  // first byte MUST be either 80 or FF
  // 80 for positive, FF for 2's comp
  var positive
  if (buf[0] === 0x80) positive = true
  else if (buf[0] === 0xFF) positive = false
  else return null
 
  // build up a base-256 tuple from the least sig to the highest
  var zero = false
    , tuple = []
  for (var i = buf.length - 1; i > 0; i --) {
    var byte = buf[i]
    if (positive) tuple.push(byte)
    else if (zero && byte === 0) tuple.push(0)
    else if (zero) {
      zero = false
      tuple.push(0x100 - byte)
    } else tuple.push(0xFF - byte)
  }
 
  for (var sum = 0, i = 0, l = tuple.length; i < l; i ++) {
    sum += tuple[i] * Math.pow(256, i)
  }
 
  return positive ? sum : -1 * sum
}
 
function parseNumeric (f) {
  if (f[0] & 0x80) return parse256(f)
 
  var str = f.toString("utf8").split("\0")[0].trim()
    , res = parseInt(str, 8)
 
  return isNaN(res) ? null : res
}
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/pack.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/pack.js

Statements: 11.54% (15 / 130)      Branches: 0% (0 / 62)      Functions: 0% (0 / 19)      Lines: 11.86% (14 / 118)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238      1   1               512   1   1                                                       1                         1                       1           1             1           1                                                                                                                                                                                                                                             1                                                   1 1    
// pipe in an fstream, and it'll make a tarball.
// key-value pair argument is global extended header props.
 
module.exports = Pack
 
var EntryWriter = require("./entry-writer.js")
  , Stream = require("stream").Stream
  , path = require("path")
  , inherits = require("inherits")
  , GlobalHeaderWriter = require("./global-header-writer.js")
  , collect = require("fstream").collect
  , eof = new Buffer(512)
 
for (var i = 0; i < 512; i ++) eof[i] = 0
 
inherits(Pack, Stream)
 
function Pack (props) {
  // console.error("-- p ctor")
  var me = this
  if (!(me instanceof Pack)) return new Pack(props)
 
  if (props) me._noProprietary = props.noProprietary
  else me._noProprietary = false
 
  me._global = props
 
  me.readable = true
  me.writable = true
  me._buffer = []
  // console.error("-- -- set current to null in ctor")
  me._currentEntry = null
  me._processing = false
 
  me._pipeRoot = null
  me.on("pipe", function (src) {
    if (src.root === me._pipeRoot) return
    me._pipeRoot = src
    src.on("end", function () {
      me._pipeRoot = null
    })
    me.add(src)
  })
}
 
Pack.prototype.addGlobal = function (props) {
  // console.error("-- p addGlobal")
  if (this._didGlobal) return
  this._didGlobal = true
 
  var me = this
  GlobalHeaderWriter(props)
    .on("data", function (c) {
      me.emit("data", c)
    })
    .end()
}
 
Pack.prototype.add = function (stream) {
  if (this._global && !this._didGlobal) this.addGlobal(this._global)
 
  if (this._ended) return this.emit("error", new Error("add after end"))
 
  collect(stream)
  this._buffer.push(stream)
  this._process()
  this._needDrain = this._buffer.length > 0
  return !this._needDrain
}
 
Pack.prototype.pause = function () {
  this._paused = true
  if (this._currentEntry) this._currentEntry.pause()
  this.emit("pause")
}
 
Pack.prototype.resume = function () {
  this._paused = false
  if (this._currentEntry) this._currentEntry.resume()
  this.emit("resume")
  this._process()
}
 
Pack.prototype.end = function () {
  this._ended = true
  this._buffer.push(eof)
  this._process()
}
 
Pack.prototype._process = function () {
  var me = this
  if (me._paused || me._processing) {
    return
  }
 
  var entry = me._buffer.shift()
 
  if (!entry) {
    if (me._needDrain) {
      me.emit("drain")
    }
    return
  }
 
  if (entry.ready === false) {
    // console.error("-- entry is not ready", entry)
    me._buffer.unshift(entry)
    entry.on("ready", function () {
      // console.error("-- -- ready!", entry)
      me._process()
    })
    return
  }
 
  me._processing = true
 
  if (entry === eof) {
    // need 2 ending null blocks.
    me.emit("data", eof)
    me.emit("data", eof)
    me.emit("end")
    me.emit("close")
    return
  }
 
  // Change the path to be relative to the root dir that was
  // added to the tarball.
  //
  // XXX This should be more like how -C works, so you can
  // explicitly set a root dir, and also explicitly set a pathname
  // in the tarball to use.  That way we can skip a lot of extra
  // work when resolving symlinks for bundled dependencies in npm.
 
  var root = path.dirname((entry.root || entry).path);
  if (me._global && me._global.fromBase && entry.root && entry.root.path) {
    // user set 'fromBase: true' indicating tar root should be directory itself
    root = entry.root.path;
  }
 
  var wprops = {}
 
  Object.keys(entry.props || {}).forEach(function (k) {
    wprops[k] = entry.props[k]
  })
 
  if (me._noProprietary) wprops.noProprietary = true
 
  wprops.path = path.relative(root, entry.path || '')
 
  // actually not a matter of opinion or taste.
  if (process.platform === "win32") {
    wprops.path = wprops.path.replace(/\\/g, "/")
  }
 
  if (!wprops.type)
    wprops.type = 'Directory'
 
  switch (wprops.type) {
    // sockets not supported
    case "Socket":
      return
 
    case "Directory":
      wprops.path += "/"
      wprops.size = 0
      break
 
    case "Link":
      var lp = path.resolve(path.dirname(entry.path), entry.linkpath)
      wprops.linkpath = path.relative(root, lp) || "."
      wprops.size = 0
      break
 
    case "SymbolicLink":
      var lp = path.resolve(path.dirname(entry.path), entry.linkpath)
      wprops.linkpath = path.relative(path.dirname(entry.path), lp) || "."
      wprops.size = 0
      break
  }
 
  // console.error("-- new writer", wprops)
  // if (!wprops.type) {
  //   // console.error("-- no type?", entry.constructor.name, entry)
  // }
 
  // console.error("-- -- set current to new writer", wprops.path)
  var writer = me._currentEntry = EntryWriter(wprops)
 
  writer.parent = me
 
  // writer.on("end", function () {
  //   // console.error("-- -- writer end", writer.path)
  // })
 
  writer.on("data", function (c) {
    me.emit("data", c)
  })
 
  writer.on("header", function () {
    Buffer.prototype.toJSON = function () {
      return this.toString().split(/\0/).join(".")
    }
    // console.error("-- -- writer header %j", writer.props)
    if (writer.props.size === 0) nextEntry()
  })
  writer.on("close", nextEntry)
 
  var ended = false
  function nextEntry () {
    if (ended) return
    ended = true
 
    // console.error("-- -- writer close", writer.path)
    // console.error("-- -- set current to null", wprops.path)
    me._currentEntry = null
    me._processing = false
    me._process()
  }
 
  writer.on("error", function (er) {
    // console.error("-- -- writer error", writer.path)
    me.emit("error", er)
  })
 
  // if it's the root, then there's no need to add its entries,
  // or data, since they'll be added directly.
  if (entry === me._pipeRoot) {
    // console.error("-- is the root, don't auto-add")
    writer.add = null
  }
 
  entry.pipe(writer)
}
 
Pack.prototype.destroy = function () {}
Pack.prototype.write = function () {}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/parse.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/lib/parse.js

Statements: 7.87% (10 / 127)      Branches: 0% (0 / 63)      Functions: 0% (0 / 19)      Lines: 8.26% (10 / 121)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277          1   1                                 1   1                                                                     1                 1                         1                 1   1                                                                                       1                                                                                                                                                                                                                                                                                    
 
// A writable stream.
// It emits "entry" events, which provide a readable stream that has
// header info attached.
 
module.exports = Parse.create = Parse
 
var stream = require("stream")
  , Stream = stream.Stream
  , BlockStream = require("block-stream")
  , tar = require("../tar.js")
  , TarHeader = require("./header.js")
  , Entry = require("./entry.js")
  , BufferEntry = require("./buffer-entry.js")
  , ExtendedHeader = require("./extended-header.js")
  , assert = require("assert").ok
  , inherits = require("inherits")
  , fstream = require("fstream")
 
// reading a tar is a lot like reading a directory
// However, we're actually not going to run the ctor,
// since it does a stat and various other stuff.
// This inheritance gives us the pause/resume/pipe
// behavior that is desired.
inherits(Parse, fstream.Reader)
 
function Parse () {
  var me = this
  if (!(me instanceof Parse)) return new Parse()
 
  // doesn't apply fstream.Reader ctor?
  // no, becasue we don't want to stat/etc, we just
  // want to get the entry/add logic from .pipe()
  Stream.apply(me)
 
  me.writable = true
  me.readable = true
  me._stream = new BlockStream(512)
  me.position = 0
  me._ended = false
 
  me._stream.on("error", function (e) {
    me.emit("error", e)
  })
 
  me._stream.on("data", function (c) {
    me._process(c)
  })
 
  me._stream.on("end", function () {
    me._streamEnd()
  })
 
  me._stream.on("drain", function () {
    me.emit("drain")
  })
}
 
// overridden in Extract class, since it needs to
// wait for its DirWriter part to finish before
// emitting "end"
Parse.prototype._streamEnd = function () {
  var me = this
  if (!me._ended || me._entry) me.error("unexpected eof")
  me.emit("end")
}
 
// a tar reader is actually a filter, not just a readable stream.
// So, you should pipe a tarball stream into it, and it needs these
// write/end methods to do that.
Parse.prototype.write = function (c) {
  if (this._ended) {
    // gnutar puts a LOT of nulls at the end.
    // you can keep writing these things forever.
    // Just ignore them.
    for (var i = 0, l = c.length; i > l; i ++) {
      if (c[i] !== 0) return this.error("write() after end()")
    }
    return
  }
  return this._stream.write(c)
}
 
Parse.prototype.end = function (c) {
  this._ended = true
  return this._stream.end(c)
}
 
// don't need to do anything, since we're just
// proxying the data up from the _stream.
// Just need to override the parent's "Not Implemented"
// error-thrower.
Parse.prototype._read = function () {}
 
Parse.prototype._process = function (c) {
  assert(c && c.length === 512, "block size should be 512")
 
  // one of three cases.
  // 1. A new header
  // 2. A part of a file/extended header
  // 3. One of two or more EOF null blocks
 
  if (this._entry) {
    var entry = this._entry
    if(!entry._abort) entry.write(c)
    else {
      entry._remaining -= c.length
      if(entry._remaining < 0) entry._remaining = 0
    }
    if (entry._remaining === 0) {
      entry.end()
      this._entry = null
    }
  } else {
    // either zeroes or a header
    var zero = true
    for (var i = 0; i < 512 && zero; i ++) {
      zero = c[i] === 0
    }
 
    // eof is *at least* 2 blocks of nulls, and then the end of the
    // file.  you can put blocks of nulls between entries anywhere,
    // so appending one tarball to another is technically valid.
    // ending without the eof null blocks is not allowed, however.
    if (zero) {
      if (this._eofStarted)
        this._ended = true
      this._eofStarted = true
    } else {
      this._eofStarted = false
      this._startEntry(c)
    }
  }
 
  this.position += 512
}
 
// take a header chunk, start the right kind of entry.
Parse.prototype._startEntry = function (c) {
  var header = new TarHeader(c)
    , self = this
    , entry
    , ev
    , EntryType
    , onend
    , meta = false
 
  if (null === header.size || !header.cksumValid) {
    var e = new Error("invalid tar file")
    e.header = header
    e.tar_file_offset = this.position
    e.tar_block = this.position / 512
    return this.emit("error", e)
  }
 
  switch (tar.types[header.type]) {
    case "File":
    case "OldFile":
    case "Link":
    case "SymbolicLink":
    case "CharacterDevice":
    case "BlockDevice":
    case "Directory":
    case "FIFO":
    case "ContiguousFile":
    case "GNUDumpDir":
      // start a file.
      // pass in any extended headers
      // These ones consumers are typically most interested in.
      EntryType = Entry
      ev = "entry"
      break
 
    case "GlobalExtendedHeader":
      // extended headers that apply to the rest of the tarball
      EntryType = ExtendedHeader
      onend = function () {
        self._global = self._global || {}
        Object.keys(entry.fields).forEach(function (k) {
          self._global[k] = entry.fields[k]
        })
      }
      ev = "globalExtendedHeader"
      meta = true
      break
 
    case "ExtendedHeader":
    case "OldExtendedHeader":
      // extended headers that apply to the next entry
      EntryType = ExtendedHeader
      onend = function () {
        self._extended = entry.fields
      }
      ev = "extendedHeader"
      meta = true
      break
 
    case "NextFileHasLongLinkpath":
      // set linkpath=<contents> in extended header
      EntryType = BufferEntry
      onend = function () {
        self._extended = self._extended || {}
        self._extended.linkpath = entry.body
      }
      ev = "longLinkpath"
      meta = true
      break
 
    case "NextFileHasLongPath":
    case "OldGnuLongPath":
      // set path=<contents> in file-extended header
      EntryType = BufferEntry
      onend = function () {
        self._extended = self._extended || {}
        self._extended.path = entry.body
      }
      ev = "longPath"
      meta = true
      break
 
    default:
      // all the rest we skip, but still set the _entry
      // member, so that we can skip over their data appropriately.
      // emit an event to say that this is an ignored entry type?
      EntryType = Entry
      ev = "ignoredEntry"
      break
  }
 
  var global, extended
  if (meta) {
    global = extended = null
  } else {
    var global = this._global
    var extended = this._extended
 
    // extendedHeader only applies to one entry, so once we start
    // an entry, it's over.
    this._extended = null
  }
  entry = new EntryType(header, extended, global)
  entry.meta = meta
 
  // only proxy data events of normal files.
  if (!meta) {
    entry.on("data", function (c) {
      me.emit("data", c)
    })
  }
 
  if (onend) entry.on("end", onend)
 
  this._entry = entry
  var me = this
 
  entry.on("pause", function () {
    me.pause()
  })
 
  entry.on("resume", function () {
    me.resume()
  })
 
  if (this.listeners("*").length) {
    this.emit("*", ev, entry)
  }
 
  this.emit(ev, entry)
 
  // Zero-byte entry.  End immediately.
  if (entry.props.size === 0) {
    entry.end()
    this._entry = null
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/node_modules/block-stream/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/node_modules/block-stream/

Statements: 9.52% (10 / 105)      Branches: 1.39% (1 / 72)      Functions: 0% (0 / 8)      Lines: 10.2% (10 / 98)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/tar/node_modules/block-stream/
File Statements Branches Functions Lines
block-stream.js 9.52% (10 / 105) 1.39% (1 / 72) 0% (0 / 8) 10.2% (10 / 98)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/node_modules/block-stream/block-stream.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/tar/node_modules/block-stream/block-stream.js

Statements: 9.52% (10 / 105)      Branches: 1.39% (1 / 72)      Functions: 0% (0 / 8)      Lines: 10.2% (10 / 98)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211        1   1         1                               1   1                                       1         1           1               1       1                                                                                                                                                                                                                                                                                    
// write data to it, and it'll emit data in 512 byte blocks.
// if you .end() or .flush(), it'll emit whatever it's got,
// padded with nulls to 512 bytes.
 
module.exports = BlockStream
 
var Stream = require("stream").Stream
  , inherits = require("inherits")
  , assert = require("assert").ok
  , debug = process.env.DEBUG ? console.error : function () {}
 
function BlockStream (size, opt) {
  this.writable = this.readable = true
  this._opt = opt || {}
  this._chunkSize = size || 512
  this._offset = 0
  this._buffer = []
  this._bufferLength = 0
  if (this._opt.nopad) this._zeroes = false
  else {
    this._zeroes = new Buffer(this._chunkSize)
    for (var i = 0; i < this._chunkSize; i ++) {
      this._zeroes[i] = 0
    }
  }
}
 
inherits(BlockStream, Stream)
 
BlockStream.prototype.write = function (c) {
  // debug("   BS write", c)
  if (this._ended) throw new Error("BlockStream: write after end")
  if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "")
  if (c.length) {
    this._buffer.push(c)
    this._bufferLength += c.length
  }
  // debug("pushed onto buffer", this._bufferLength)
  if (this._bufferLength >= this._chunkSize) {
    if (this._paused) {
      // debug("   BS paused, return false, need drain")
      this._needDrain = true
      return false
    }
    this._emitChunk()
  }
  return true
}
 
BlockStream.prototype.pause = function () {
  // debug("   BS pausing")
  this._paused = true
}
 
BlockStream.prototype.resume = function () {
  // debug("   BS resume")
  this._paused = false
  return this._emitChunk()
}
 
BlockStream.prototype.end = function (chunk) {
  // debug("end", chunk)
  if (typeof chunk === "function") cb = chunk, chunk = null
  if (chunk) this.write(chunk)
  this._ended = true
  this.flush()
}
 
BlockStream.prototype.flush = function () {
  this._emitChunk(true)
}
 
BlockStream.prototype._emitChunk = function (flush) {
  // debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused)
 
  // emit a <chunkSize> chunk
  if (flush && this._zeroes) {
    // debug("    BS push zeroes", this._bufferLength)
    // push a chunk of zeroes
    var padBytes = (this._bufferLength % this._chunkSize)
    if (padBytes !== 0) padBytes = this._chunkSize - padBytes
    if (padBytes > 0) {
      // debug("padBytes", padBytes, this._zeroes.slice(0, padBytes))
      this._buffer.push(this._zeroes.slice(0, padBytes))
      this._bufferLength += padBytes
      // debug(this._buffer[this._buffer.length - 1].length, this._bufferLength)
    }
  }
 
  if (this._emitting || this._paused) return
  this._emitting = true
 
  // debug("    BS entering loops")
  var bufferIndex = 0
  while (this._bufferLength >= this._chunkSize &&
         (flush || !this._paused)) {
    // debug("     BS data emission loop", this._bufferLength)
 
    var out
      , outOffset = 0
      , outHas = this._chunkSize
 
    while (outHas > 0 && (flush || !this._paused) ) {
      // debug("    BS data inner emit loop", this._bufferLength)
      var cur = this._buffer[bufferIndex]
        , curHas = cur.length - this._offset
      // debug("cur=", cur)
      // debug("curHas=%j", curHas)
      // If it's not big enough to fill the whole thing, then we'll need
      // to copy multiple buffers into one.  However, if it is big enough,
      // then just slice out the part we want, to save unnecessary copying.
      // Also, need to copy if we've already done some copying, since buffers
      // can't be joined like cons strings.
      if (out || curHas < outHas) {
        out = out || new Buffer(this._chunkSize)
        cur.copy(out, outOffset,
                 this._offset, this._offset + Math.min(curHas, outHas))
      } else if (cur.length === outHas && this._offset === 0) {
        // shortcut -- cur is exactly long enough, and no offset.
        out = cur
      } else {
        // slice out the piece of cur that we need.
        out = cur.slice(this._offset, this._offset + outHas)
      }
 
      if (curHas > outHas) {
        // means that the current buffer couldn't be completely output
        // update this._offset to reflect how much WAS written
        this._offset += outHas
        outHas = 0
      } else {
        // output the entire current chunk.
        // toss it away
        outHas -= curHas
        outOffset += curHas
        bufferIndex ++
        this._offset = 0
      }
    }
 
    this._bufferLength -= this._chunkSize
    assert(out.length === this._chunkSize)
    // debug("emitting data", out)
    // debug("   BS emitting, paused=%j", this._paused, this._bufferLength)
    this.emit("data", out)
    out = null
  }
  // debug("    BS out of loops", this._bufferLength)
 
  // whatever is left, it's not enough to fill up a block, or we're paused
  this._buffer = this._buffer.slice(bufferIndex)
  if (this._paused) {
    // debug("    BS paused, leaving", this._bufferLength)
    this._needsDrain = true
    this._emitting = false
    return
  }
 
  // if flushing, and not using null-padding, then need to emit the last
  // chunk(s) sitting in the queue.  We know that it's not enough to
  // fill up a whole block, because otherwise it would have been emitted
  // above, but there may be some offset.
  var l = this._buffer.length
  if (flush && !this._zeroes && l) {
    if (l === 1) {
      if (this._offset) {
        this.emit("data", this._buffer[0].slice(this._offset))
      } else {
        this.emit("data", this._buffer[0])
      }
    } else {
      var outHas = this._bufferLength
        , out = new Buffer(outHas)
        , outOffset = 0
      for (var i = 0; i < l; i ++) {
        var cur = this._buffer[i]
          , curHas = cur.length - this._offset
        cur.copy(out, outOffset, this._offset)
        this._offset = 0
        outOffset += curHas
        this._bufferLength -= curHas
      }
      this.emit("data", out)
    }
    // truncate
    this._buffer.length = 0
    this._bufferLength = 0
    this._offset = 0
  }
 
  // now either drained or ended
  // debug("either draining, or ended", this._bufferLength, this._ended)
  // means that we've flushed out all that we can so far.
  if (this._needDrain) {
    // debug("emitting drain", this._bufferLength)
    this._needDrain = false
    this.emit("drain")
  }
 
  if ((this._bufferLength === 0) && this._ended && !this._endEmitted) {
    // debug("emitting end", this._bufferLength)
    this._endEmitted = true
    this.emit("end")
  }
 
  this._emitting = false
 
  // debug("    BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/text-table/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/text-table/

Statements: 8.47% (5 / 59)      Branches: 0% (0 / 38)      Functions: 0% (0 / 14)      Lines: 9.43% (5 / 53)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/text-table/
File Statements Branches Functions Lines
index.js 8.47% (5 / 59) 0% (0 / 38) 0% (0 / 14) 9.43% (5 / 53)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/text-table/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/text-table/index.js

Statements: 8.47% (5 / 59)      Branches: 0% (0 / 38)      Functions: 0% (0 / 14)      Lines: 9.43% (5 / 53)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 881                                                                                                               1         1                   1             1                  
module.exports = function (rows_, opts) {
    if (!opts) opts = {};
    var hsep = opts.hsep === undefined ? '  ' : opts.hsep;
    var align = opts.align || [];
    var stringLength = opts.stringLength
        || function (s) { return String(s).length; }
    ;
    
    var dotsizes = reduce(rows_, function (acc, row) {
        forEach(row, function (c, ix) {
            var n = dotindex(c);
            if (!acc[ix] || n > acc[ix]) acc[ix] = n;
        });
        return acc;
    }, []);
    
    var rows = map(rows_, function (row) {
        return map(row, function (c_, ix) {
            var c = String(c_);
            if (align[ix] === '.') {
                var index = dotindex(c);
                var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2)
                    - (stringLength(c) - index)
                ;
                return c + Array(size).join(' ');
            }
            else return c;
        });
    });
    
    var sizes = reduce(rows, function (acc, row) {
        forEach(row, function (c, ix) {
            var n = stringLength(c);
            if (!acc[ix] || n > acc[ix]) acc[ix] = n;
        });
        return acc;
    }, []);
    
    return map(rows, function (row) {
        return map(row, function (c, ix) {
            var n = (sizes[ix] - stringLength(c)) || 0;
            var s = Array(Math.max(n + 1, 1)).join(' ');
            if (align[ix] === 'r' || align[ix] === '.') {
                return s + c;
            }
            if (align[ix] === 'c') {
                return Array(Math.ceil(n / 2 + 1)).join(' ')
                    + c + Array(Math.floor(n / 2 + 1)).join(' ')
                ;
            }
            
            return c + s;
        }).join(hsep).replace(/\s+$/, '');
    }).join('\n');
};
 
function dotindex (c) {
    var m = /\.[^.]*$/.exec(c);
    return m ? m.index + 1 : c.length;
}
 
function reduce (xs, f, init) {
    if (xs.reduce) return xs.reduce(f, init);
    var i = 0;
    var acc = arguments.length >= 3 ? init : xs[i++];
    for (; i < xs.length; i++) {
        f(acc, xs[i], i);
    }
    return acc;
}
 
function forEach (xs, f) {
    if (xs.forEach) return xs.forEach(f);
    for (var i = 0; i < xs.length; i++) {
        f.call(xs, xs[i], i);
    }
}
 
function map (xs, f) {
    if (xs.map) return xs.map(f);
    var res = [];
    for (var i = 0; i < xs.length; i++) {
        res.push(f.call(xs, xs[i], i));
    }
    return res;
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uid-number/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uid-number/

Statements: 7.69% (3 / 39)      Branches: 6.25% (2 / 32)      Functions: 0% (0 / 2)      Lines: 10.34% (3 / 29)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/uid-number/
File Statements Branches Functions Lines
uid-number.js 7.69% (3 / 39) 6.25% (2 / 32) 0% (0 / 2) 10.34% (3 / 29)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uid-number/uid-number.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uid-number/uid-number.js

Statements: 7.69% (3 / 39)      Branches: 6.25% (2 / 32)      Functions: 0% (0 / 2)      Lines: 10.34% (3 / 29)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 611               1           1                                                                                            
module.exports = uidNumber
 
// This module calls into get-uid-gid.js, which sets the
// uid and gid to the supplied argument, in order to find out their
// numeric value.  This can't be done in the main node process,
// because otherwise node would be running as that user from this
// point on.
 
var child_process = require("child_process")
  , path = require("path")
  , uidSupport = process.getuid && process.setuid
  , uidCache = {}
  , gidCache = {}
 
function uidNumber (uid, gid, cb) {
  if (!uidSupport) return cb()
  if (typeof cb !== "function") cb = gid, gid = null
  if (typeof cb !== "function") cb = uid, uid = null
  if (gid == null) gid = process.getgid()
  if (uid == null) uid = process.getuid()
  if (!isNaN(gid)) gid = gidCache[gid] = +gid
  if (!isNaN(uid)) uid = uidCache[uid] = +uid
 
  if (uidCache.hasOwnProperty(uid)) uid = uidCache[uid]
  if (gidCache.hasOwnProperty(gid)) gid = gidCache[gid]
 
  if (typeof gid === "number" && typeof uid === "number") {
    return process.nextTick(cb.bind(null, null, uid, gid))
  }
 
  var getter = require.resolve("./get-uid-gid.js")
 
  child_process.execFile( process.execPath
                        , [getter, uid, gid]
                        , function (code, out, stderr) {
    if (code) {
      var er = new Error("could not get uid/gid\n" + stderr)
      er.code = code
      return cb(er)
    }
 
    try {
      out = JSON.parse(out+"")
    } catch (ex) {
      return cb(ex)
    }
 
    if (out.error) {
      var er = new Error(out.error)
      er.errno = out.errno
      return cb(er)
    }
 
    if (isNaN(out.uid) || isNaN(out.gid)) return cb(new Error(
      "Could not get uid/gid: "+JSON.stringify(out)))
 
    cb(null, uidCache[uid] = +out.uid, gidCache[gid] = +out.gid)
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/umask/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/umask/

Statements: 36.84% (14 / 38)      Branches: 0% (0 / 26)      Functions: 20% (1 / 5)      Lines: 36.84% (14 / 38)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/umask/
File Statements Branches Functions Lines
index.js 36.84% (14 / 38) 0% (0 / 26) 20% (1 / 5) 36.84% (14 / 38)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/umask/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/umask/index.js

Statements: 36.84% (14 / 38)      Branches: 0% (0 / 26)      Functions: 20% (1 / 5)      Lines: 36.84% (14 / 38)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79    1   1 1 1 2   1     1 1   1                                   1                                                         1                     1 1 1      
'use strict';
 
var util = require("util");
 
function toString(val) {
    val = val.toString(8);
    while (val.length < 4) {
        val = "0" + val;
    }
    return val;
}
 
var defaultUmask = 18; // 0022;
var defaultUmaskString = toString(defaultUmask);
 
function validate(data, k, val) {
    // must be either an integer or an octal string.
    if (typeof val === "number" && !isNaN(val)) {
        data[k] = val;
        return true;
    }
 
    if (typeof val === "string") {
        if (val.charAt(0) !== "0") {
            return false;
        }
        data[k] = parseInt(val, 8);
        return true;
    }
 
    return false;
}
 
function convert_fromString(val, cb) {
    if (typeof val === "string") {
        // check for octal string first
        if (val.charAt(0) === '0' && /^[0-7]+$/.test(val)) {
            val = parseInt(val, 8);
        } else if (val.charAt(0) !== '0' && /^[0-9]+$/.test(val)) {
            // legacy support for decimal strings
            val = parseInt(val, 10);
        } else {
            return cb(new Error(util.format("Expected octal string, got %j, defaulting to %j",
                                            val, defaultUmaskString)),
                      defaultUmask);
        }
    } else if (typeof val !== "number") {
        return cb(new Error(util.format("Expected number or octal string, got %j, defaulting to %j",
                                        val, defaultUmaskString)),
                  defaultUmask);
    }
 
    val = Math.floor(val);
 
    if ((val < 0) || (val > 511)) {
        return cb(new Error(util.format("Must be in range 0..511 (0000..0777), got %j", val)),
                  defaultUmask);
    }
 
    cb(null, val);
}
 
function fromString(val, cb) {
 
    // synchronous callback, no zalgo
    convert_fromString(val, cb || function (err, result) {
        /*jslint unparam:true*/
        val = result;
    });
 
    return val;
}
 
exports.toString = toString;
exports.fromString = fromString;
exports.validate = validate;
 
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/

Statements: 75% (3 / 4)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 75% (3 / 4)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/unique-filename/
File Statements Branches Functions Lines
index.js 75% (3 / 4) 0% (0 / 2) 0% (0 / 1) 75% (3 / 4)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/index.js

Statements: 75% (3 / 4)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 75% (3 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10  1   1   1        
'use strict'
var path = require('path')
 
var uniqueSlug = require('unique-slug')
 
module.exports = function (filepath, prefix, uniq) {
  return path.join(filepath, (prefix ? prefix + '-' : '') + uniqueSlug(uniq))
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/node_modules/unique-slug/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/node_modules/unique-slug/

Statements: 42.86% (3 / 7)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 42.86% (3 / 7)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/unique-filename/node_modules/unique-slug/
File Statements Branches Functions Lines
index.js 42.86% (3 / 7) 0% (0 / 2) 0% (0 / 1) 42.86% (3 / 7)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/node_modules/unique-slug/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unique-filename/node_modules/unique-slug/index.js

Statements: 42.86% (3 / 7)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 42.86% (3 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21  1 1   1                                
'use strict'
var crypto = require('crypto')
var MurmurHash3 = require('imurmurhash')
 
module.exports = function (uniq) {
  if (uniq) {
    var hash = new MurmurHash3(uniq)
    return ('00000000' + hash.result().toString(16)).substr(-8)
  } else {
    // Called without a callback, because this interface should neither block
    // nor error (by contrast with randomBytes which will throw an exception
    // without enough entropy).
    //
    // However, due to a change in Node 0.10.27+, pseudoRandomBytes is now the
    // same as randomBytes, and may in fact block in situations where
    // insufficent entropy is available.
    return crypto.pseudoRandomBytes(4).toString('hex')
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unpipe/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unpipe/

Statements: 13.64% (3 / 22)      Branches: 0% (0 / 12)      Functions: 0% (0 / 2)      Lines: 13.64% (3 / 22)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/unpipe/
File Statements Branches Functions Lines
index.js 13.64% (3 / 22) 0% (0 / 12) 0% (0 / 2) 13.64% (3 / 22)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unpipe/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/unpipe/index.js

Statements: 13.64% (3 / 22)      Branches: 0% (0 / 12)      Functions: 0% (0 / 2)      Lines: 13.64% (3 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                          1             1                                     1                                                              
/*!
 * unpipe
 * Copyright(c) 2015 Douglas Christopher Wilson
 * MIT Licensed
 */
 
'use strict'
 
/**
 * Module exports.
 * @public
 */
 
module.exports = unpipe
 
/**
 * Determine if there are Node.js pipe-like data listeners.
 * @private
 */
 
function hasPipeDataListeners(stream) {
  var listeners = stream.listeners('data')
 
  for (var i = 0; i < listeners.length; i++) {
    if (listeners[i].name === 'ondata') {
      return true
    }
  }
 
  return false
}
 
/**
 * Unpipe a stream from all destinations.
 *
 * @param {object} stream
 * @public
 */
 
function unpipe(stream) {
  if (!stream) {
    throw new TypeError('argument stream is required')
  }
 
  if (typeof stream.unpipe === 'function') {
    // new-style
    stream.unpipe()
    return
  }
 
  // Node.js 0.8 hack
  if (!hasPipeDataListeners(stream)) {
    return
  }
 
  var listener
  var listeners = stream.listeners('close')
 
  for (var i = 0; i < listeners.length; i++) {
    listener = listeners[i]
 
    if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
      continue
    }
 
    // invoke the listener
    listener.call(stream)
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/

Statements: 28.57% (18 / 63)      Branches: 0% (0 / 45)      Functions: 0% (0 / 2)      Lines: 28.57% (18 / 63)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/uuid/
File Statements Branches Functions Lines
index.js 100% (6 / 6) 100% (0 / 0) 100% (0 / 0) 100% (6 / 6)
v1.js 19.51% (8 / 41) 0% (0 / 28) 0% (0 / 1) 19.51% (8 / 41)
v4.js 25% (4 / 16) 0% (0 / 17) 0% (0 / 1) 25% (4 / 16)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/index.js

Statements: 100% (6 / 6)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (6 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 101 1   1 1 1   1    
var v1 = require('./v1');
var v4 = require('./v4');
 
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
 
module.exports = uuid;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/v1.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/v1.js

Statements: 19.51% (8 / 41)      Branches: 0% (0 / 28)      Functions: 0% (0 / 1)      Lines: 19.51% (8 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105      1 1               1     1           1     1     1                                                                                                                                                     1    
// Unique ID creation requires a high quality random # generator.  We feature
// detect to determine the best RNG source, normalizing to a function that
// returns 128-bits of randomness, since that's what's usually required
var rng = require('./lib/rng');
var bytesToUuid = require('./lib/bytesToUuid');
 
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
 
// random #'s we need to init node and clockseq
var _seedBytes = rng();
 
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
var _nodeId = [
  _seedBytes[0] | 0x01,
  _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
];
 
// Per 4.2.2, randomize (14 bit) clockseq
var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
 
// Previous uuid creation time
var _lastMSecs = 0, _lastNSecs = 0;
 
// See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
  var i = buf && offset || 0;
  var b = buf || [];
 
  options = options || {};
 
  var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
 
  // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so
  // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
 
  // Per 4.2.1.2, use count of uuid's generated during the current clock
  // cycle to simulate higher resolution clock
  var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
 
  // Time since last uuid creation (in msecs)
  var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
 
  // Per 4.2.1.2, Bump clockseq on clock regression
  if (dt < 0 && options.clockseq === undefined) {
    clockseq = clockseq + 1 & 0x3fff;
  }
 
  // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  // time interval
  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
    nsecs = 0;
  }
 
  // Per 4.2.1.2 Throw error if too many uuids are requested
  if (nsecs >= 10000) {
    throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  }
 
  _lastMSecs = msecs;
  _lastNSecs = nsecs;
  _clockseq = clockseq;
 
  // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  msecs += 12219292800000;
 
  // `time_low`
  var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  b[i++] = tl >>> 24 & 0xff;
  b[i++] = tl >>> 16 & 0xff;
  b[i++] = tl >>> 8 & 0xff;
  b[i++] = tl & 0xff;
 
  // `time_mid`
  var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  b[i++] = tmh >>> 8 & 0xff;
  b[i++] = tmh & 0xff;
 
  // `time_high_and_version`
  b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  b[i++] = tmh >>> 16 & 0xff;
 
  // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  b[i++] = clockseq >>> 8 | 0x80;
 
  // `clock_seq_low`
  b[i++] = clockseq & 0xff;
 
  // `node`
  var node = options.node || _nodeId;
  for (var n = 0; n < 6; ++n) {
    b[i + n] = node[n];
  }
 
  return buf ? buf : bytesToUuid(b);
}
 
module.exports = v1;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/v4.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/v4.js

Statements: 25% (4 / 16)      Branches: 0% (0 / 17)      Functions: 0% (0 / 1)      Lines: 25% (4 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 311 1   1                                                 1    
var rng = require('./lib/rng');
var bytesToUuid = require('./lib/bytesToUuid');
 
function v4(options, buf, offset) {
  var i = buf && offset || 0;
 
  if (typeof(options) == 'string') {
    buf = options == 'binary' ? new Array(16) : null;
    options = null;
  }
  options = options || {};
 
  var rnds = options.random || (options.rng || rng)();
 
  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  rnds[6] = (rnds[6] & 0x0f) | 0x40;
  rnds[8] = (rnds[8] & 0x3f) | 0x80;
 
  // Copy bytes to buffer, if provided
  if (buf) {
    for (var ii = 0; ii < 16; ++ii) {
      buf[i + ii] = rnds[ii];
    }
  }
 
  return buf || bytesToUuid(rnds);
}
 
module.exports = v4;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/

Statements: 75% (9 / 12)      Branches: 0% (0 / 2)      Functions: 50% (1 / 2)      Lines: 75% (9 / 12)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/
File Statements Branches Functions Lines
bytesToUuid.js 62.5% (5 / 8) 0% (0 / 2) 0% (0 / 1) 62.5% (5 / 8)
rng.js 100% (4 / 4) 100% (0 / 0) 100% (1 / 1) 100% (4 / 4)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/bytesToUuid.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/bytesToUuid.js

Statements: 62.5% (5 / 8)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 62.5% (5 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25        1 1 256     1                         1    
/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
  byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
 
function bytesToUuid(buf, offset) {
  var i = offset || 0;
  var bth = byteToHex;
  return  bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]];
}
 
module.exports = bytesToUuid;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/rng.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/uuid/lib/rng.js

Statements: 100% (4 / 4)      Branches: 100% (0 / 0)      Functions: 100% (1 / 1)      Lines: 100% (4 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12      1   1 1     1    
// Unique ID creation requires a high quality random # generator.  In node.js
// this is prett straight-forward - we use the crypto API.
 
var rb = require('crypto').randomBytes;
 
function rng() {
  return rb(16);
};
 
module.exports = rng;
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/

Statements: 25% (7 / 28)      Branches: 0% (0 / 16)      Functions: 0% (0 / 3)      Lines: 25% (7 / 28)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/
File Statements Branches Functions Lines
index.js 25% (7 / 28) 0% (0 / 16) 0% (0 / 3) 25% (7 / 28)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/index.js

Statements: 25% (7 / 28)      Branches: 0% (0 / 16)      Functions: 0% (0 / 3)      Lines: 25% (7 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 861 1   1             1   1       1                             1                                                                                                            
var parse = require('spdx-expression-parse');
var correct = require('spdx-correct');
 
var genericWarning = (
  'license should be ' +
  'a valid SPDX license expression (without "LicenseRef"), ' +
  '"UNLICENSED", or ' +
  '"SEE LICENSE IN <filename>"'
);
 
var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/;
 
function startsWith(prefix, string) {
  return string.slice(0, prefix.length) === prefix;
}
 
function usesLicenseRef(ast) {
  if (ast.hasOwnProperty('license')) {
    var license = ast.license;
    return (
      startsWith('LicenseRef', license) ||
      startsWith('DocumentRef', license)
    );
  } else {
    return (
      usesLicenseRef(ast.left) ||
      usesLicenseRef(ast.right)
    );
  }
}
 
module.exports = function(argument) {
  var ast;
 
  try {
    ast = parse(argument);
  } catch (e) {
    var match
    if (
      argument === 'UNLICENSED' ||
      argument === 'UNLICENCED'
    ) {
      return {
        validForOldPackages: true,
        validForNewPackages: true,
        unlicensed: true
      };
    } else if (match = fileReferenceRE.exec(argument)) {
      return {
        validForOldPackages: true,
        validForNewPackages: true,
        inFile: match[1]
      };
    } else {
      var result = {
        validForOldPackages: false,
        validForNewPackages: false,
        warnings: [genericWarning]
      };
      var corrected = correct(argument);
      if (corrected) {
        result.warnings.push(
          'license is similar to the valid expression "' + corrected + '"'
        );
      }
      return result;
    }
  }
 
  if (usesLicenseRef(ast)) {
    return {
      validForNewPackages: false,
      validForOldPackages: false,
      spdx: true,
      warnings: [genericWarning]
    };
  } else {
    return {
      validForNewPackages: true,
      validForOldPackages: true,
      spdx: true
    };
  }
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-correct/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-correct/

Statements: 17.57% (13 / 74)      Branches: 0% (0 / 22)      Functions: 0% (0 / 27)      Lines: 17.57% (13 / 74)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-correct/
File Statements Branches Functions Lines
index.js 17.57% (13 / 74) 0% (0 / 22) 0% (0 / 27) 17.57% (13 / 74)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-correct/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-correct/index.js

Statements: 17.57% (13 / 74)      Branches: 0% (0 / 22)      Functions: 0% (0 / 27)      Lines: 17.57% (13 / 74)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 2391   1         1                                                     1 1     1                                                                                                                                                                                                             1                                                   1 1   1                   1                     1                                   1                                                          
var licenseIDs = require('spdx-license-ids');
 
function valid(string) {
  return licenseIDs.indexOf(string) > -1;
}
 
// Common transpositions of license identifier acronyms
var transpositions = [
  ['APGL', 'AGPL'],
  ['Gpl', 'GPL'],
  ['GLP', 'GPL'],
  ['APL', 'Apache'],
  ['ISD', 'ISC'],
  ['GLP', 'GPL'],
  ['IST', 'ISC'],
  ['Claude', 'Clause'],
  [' or later', '+'],
  [' International', ''],
  ['GNU', 'GPL'],
  ['GUN', 'GPL'],
  ['+', ''],
  ['GNU GPL', 'GPL'],
  ['GNU/GPL', 'GPL'],
  ['GNU GLP', 'GPL'],
  ['GNU General Public License', 'GPL'],
  ['Gnu public license', 'GPL'],
  ['GNU Public License', 'GPL'],
  ['GNU GENERAL PUBLIC LICENSE', 'GPL'],
  ['MTI', 'MIT'],
  ['Mozilla Public License', 'MPL'],
  ['WTH', 'WTF'],
  ['-License', '']
];
 
var TRANSPOSED = 0;
var CORRECT = 1;
 
// Simple corrections to nearly valid identifiers.
var transforms = [
  // e.g. 'mit'
  function(argument) {
    return argument.toUpperCase();
  },
  // e.g. 'MIT '
  function(argument) {
    return argument.trim();
  },
  // e.g. 'M.I.T.'
  function(argument) {
    return argument.replace(/\./g, '');
  },
  // e.g. 'Apache- 2.0'
  function(argument) {
    return argument.replace(/\s+/g, '');
  },
  // e.g. 'CC BY 4.0''
  function(argument) {
    return argument.replace(/\s+/g, '-');
  },
  // e.g. 'LGPLv2.1'
  function(argument) {
    return argument.replace('v', '-');
  },
  // e.g. 'Apache 2.0'
  function(argument) {
    return argument.replace(/,?\s*(\d)/, '-$1');
  },
  // e.g. 'GPL 2'
  function(argument) {
    return argument.replace(/,?\s*(\d)/, '-$1.0');
  },
  // e.g. 'Apache Version 2.0'
  function(argument) {
    return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2');
  },
  // e.g. 'Apache Version 2'
  function(argument) {
    return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0');
  },
  // e.g. 'ZLIB'
  function(argument) {
    return argument[0].toUpperCase() + argument.slice(1);
  },
  // e.g. 'MPL/2.0'
  function(argument) {
    return argument.replace('/', '-');
  },
  // e.g. 'Apache 2'
  function(argument) {
    return argument
      .replace(/\s*V\s*(\d)/, '-$1')
      .replace(/(\d)$/, '$1.0');
  },
  // e.g. 'GPL-2.0-'
  function(argument) {
    return argument.slice(0, argument.length - 1);
  },
  // e.g. 'GPL2'
  function(argument) {
    return argument.replace(/(\d)$/, '-$1.0');
  },
  // e.g. 'BSD 3'
  function(argument) {
    return argument.replace(/(-| )?(\d)$/, '-$2-Clause');
  },
  // e.g. 'BSD clause 3'
  function(argument) {
    return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause');
  },
  // e.g. 'BY-NC-4.0'
  function(argument) {
    return 'CC-' + argument;
  },
  // e.g. 'BY-NC'
  function(argument) {
    return 'CC-' + argument + '-4.0';
  },
  // e.g. 'Attribution-NonCommercial'
  function(argument) {
    return argument
      .replace('Attribution', 'BY')
      .replace('NonCommercial', 'NC')
      .replace('NoDerivatives', 'ND')
      .replace(/ (\d)/, '-$1')
      .replace(/ ?International/, '');
  },
  // e.g. 'Attribution-NonCommercial'
  function(argument) {
    return 'CC-' +
      argument
      .replace('Attribution', 'BY')
      .replace('NonCommercial', 'NC')
      .replace('NoDerivatives', 'ND')
      .replace(/ (\d)/, '-$1')
      .replace(/ ?International/, '') +
      '-4.0';
  }
];
 
// If all else fails, guess that strings containing certain substrings
// meant to identify certain licenses.
var lastResorts = [
  ['UNLI', 'Unlicense'],
  ['WTF', 'WTFPL'],
  ['2 CLAUSE', 'BSD-2-Clause'],
  ['2-CLAUSE', 'BSD-2-Clause'],
  ['3 CLAUSE', 'BSD-3-Clause'],
  ['3-CLAUSE', 'BSD-3-Clause'],
  ['AFFERO', 'AGPL-3.0'],
  ['AGPL', 'AGPL-3.0'],
  ['APACHE', 'Apache-2.0'],
  ['ARTISTIC', 'Artistic-2.0'],
  ['Affero', 'AGPL-3.0'],
  ['BEER', 'Beerware'],
  ['BOOST', 'BSL-1.0'],
  ['BSD', 'BSD-2-Clause'],
  ['ECLIPSE', 'EPL-1.0'],
  ['FUCK', 'WTFPL'],
  ['GNU', 'GPL-3.0'],
  ['LGPL', 'LGPL-3.0'],
  ['GPL', 'GPL-3.0'],
  ['MIT', 'MIT'],
  ['MPL', 'MPL-2.0'],
  ['X11', 'X11'],
  ['ZLIB', 'Zlib']
];
 
var SUBSTRING = 0;
var IDENTIFIER = 1;
 
var validTransformation = function(identifier) {
  for (var i = 0; i < transforms.length; i++) {
    var transformed = transforms[i](identifier);
    if (transformed !== identifier && valid(transformed)) {
      return transformed;
    }
  }
  return null;
};
 
var validLastResort = function(identifier) {
  var upperCased = identifier.toUpperCase();
  for (var i = 0; i < lastResorts.length; i++) {
    var lastResort = lastResorts[i];
    if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) {
      return lastResort[IDENTIFIER];
    }
  }
  return null;
};
 
var anyCorrection = function(identifier, check) {
  for (var i = 0; i < transpositions.length; i++) {
    var transposition = transpositions[i];
    var transposed = transposition[TRANSPOSED];
    if (identifier.indexOf(transposed) > -1) {
      var corrected = identifier.replace(
        transposed,
        transposition[CORRECT]
      );
      var checked = check(corrected);
      if (checked !== null) {
        return checked;
      }
    }
  }
  return null;
};
 
module.exports = function(identifier) {
  identifier = identifier.replace(/\+$/, '');
  if (valid(identifier)) {
    return identifier;
  }
  var transformed = validTransformation(identifier);
  if (transformed !== null) {
    return transformed;
  }
  transformed = anyCorrection(identifier, function(argument) {
    if (valid(argument)) {
      return argument;
    }
    return validTransformation(argument);
  });
  if (transformed !== null) {
    return transformed;
  }
  transformed = validLastResort(identifier);
  if (transformed !== null) {
    return transformed;
  }
  transformed = anyCorrection(identifier, validLastResort);
  if (transformed !== null) {
    return transformed;
  }
  return null;
};
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/

Statements: 2.51% (24 / 958)      Branches: 1.18% (6 / 509)      Functions: 12.12% (4 / 33)      Lines: 75% (3 / 4)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/
File Statements Branches Functions Lines
index.js 66.67% (2 / 3) 100% (0 / 0) 0% (0 / 1) 66.67% (2 / 3)
parser.generated.js 2.3% (22 / 955) 1.18% (6 / 509) 12.5% (4 / 32) 100% (1 / 1)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/index.js

Statements: 66.67% (2 / 3)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 61   1      
var parser = require('./parser.generated.js').parser
 
module.exports = function(argument) {
  return parser.parse(argument) }
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/parser.generated.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse/parser.generated.js

Statements: 2.3% (22 / 955)      Branches: 1.18% (6 / 509)      Functions: 12.5% (4 / 32)      Lines: 100% (1 / 1)      Ignored: none     

1 2 39    
var spdxparse=function(){var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,5],$V1=[1,6],$V2=[1,7],$V3=[1,4],$V4=[1,9],$V5=[1,10],$V6=[5,14,15,17],$V7=[5,12,14,15,17];var parser={trace:function trace(){},yy:{},symbols_:{error:2,start:3,expression:4,EOS:5,simpleExpression:6,LICENSE:7,PLUS:8,LICENSEREF:9,DOCUMENTREF:10,COLON:11,WITH:12,EXCEPTION:13,AND:14,OR:15,OPEN:16,CLOSE:17,$accept:0,$end:1},terminals_:{2:"error",5:"EOS",7:"LICENSE",8:"PLUS",9:"LICENSEREF",10:"DOCUMENTREF",11:"COLON",12:"WITH",13:"EXCEPTION",14:"AND",15:"OR",16:"OPEN",17:"CLOSE"},productions_:[0,[3,2],[6,1],[6,2],[6,1],[6,3],[4,1],[4,3],[4,3],[4,3],[4,3]],performAction:function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$){var $0=$$.length-1;switch(yystate){case 1:return this.$=$$[$0-1];break;case 2:case 4:case 5:this.$={license:yytext};break;case 3:this.$={license:$$[$0-1],plus:true};break;case 6:this.$=$$[$0];break;case 7:this.$={exception:$$[$0]};this.$.license=$$[$0-2].license;if($$[$0-2].hasOwnProperty("plus")){this.$.plus=$$[$0-2].plus}break;case 8:this.$={conjunction:"and",left:$$[$0-2],right:$$[$0]};break;case 9:this.$={conjunction:"or",left:$$[$0-2],right:$$[$0]};break;case 10:this.$=$$[$0-1];break}},table:[{3:1,4:2,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{1:[3]},{5:[1,8],14:$V4,15:$V5},o($V6,[2,6],{12:[1,11]}),{4:12,6:3,7:$V0,9:$V1,10:$V2,16:$V3},o($V7,[2,2],{8:[1,13]}),o($V7,[2,4]),{11:[1,14]},{1:[2,1]},{4:15,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{4:16,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{13:[1,17]},{14:$V4,15:$V5,17:[1,18]},o($V7,[2,3]),{9:[1,19]},o($V6,[2,8]),o([5,15,17],[2,9],{14:$V4}),o($V6,[2,7]),o($V6,[2,10]),o($V7,[2,5])],defaultActions:{8:[2,1]},parseError:function parseError(str,hash){if(hash.recoverable){this.trace(str)}else{throw new Error(str)}},parse:function parse(input){var self=this,stack=[0],tstack=[],vstack=[null],lstack=[],table=this.table,yytext="",yylineno=0,yyleng=0,recovering=0,TERROR=2,EOF=1;var args=lstack.slice.call(arguments,1);var lexer=Object.create(this.lexer);var sharedState={yy:{}};for(var k in this.yy){if(Object.prototype.hasOwnProperty.call(this.yy,k)){sharedState.yy[k]=this.yy[k]}}lexer.setInput(input,sharedState.yy);sharedState.yy.lexer=lexer;sharedState.yy.parser=this;if(typeof lexer.yylloc=="undefined"){lexer.yylloc={}}var yyloc=lexer.yylloc;lstack.push(yyloc);var ranges=lexer.options&&lexer.options.ranges;if(typeof sharedState.yy.parseError==="function"){this.parseError=sharedState.yy.parseError}else{this.parseError=Object.getPrototypeOf(this).parseError}function popStack(n){stack.length=stack.length-2*n;vstack.length=vstack.length-n;lstack.length=lstack.length-n}_token_stack:function lex(){var token;token=lexer.lex()||EOF;if(typeof token!=="number"){token=self.symbols_[token]||token}return token}var symbol,preErrorSymbol,state,action,a,r,yyval={},p,len,newState,expected;while(true){state=stack[stack.length-1];if(this.defaultActions[state]){action=this.defaultActions[state]}else{if(symbol===null||typeof symbol=="undefined"){symbol=lex()}action=table[state]&&table[state][symbol]}if(typeof action==="undefined"||!action.length||!action[0]){var errStr="";expected=[];for(p in table[state]){if(this.terminals_[p]&&p>TERROR){expected.push("'"+this.terminals_[p]+"'")}}if(lexer.showPosition){errStr="Parse error on line "+(yylineno+1)+":\n"+lexer.showPosition()+"\nExpecting "+expected.join(", ")+", got '"+(this.terminals_[symbol]||symbol)+"'"}else{errStr="Parse error on line "+(yylineno+1)+": Unexpected "+(symbol==EOF?"end of input":"'"+(this.terminals_[symbol]||symbol)+"'")}this.parseError(errStr,{text:lexer.match,token:this.terminals_[symbol]||symbol,line:lexer.yylineno,loc:yyloc,expected:expected})}if(action[0]instanceof Array&&action.length>1){throw new Error("Parse Error: multiple actions possible at state: "+state+", token: "+symbol)}switch(action[0]){case 1:stack.push(symbol);vstack.push(lexer.yytext);lstack.push(lexer.yylloc);stack.push(action[1]);symbol=null;if(!preErrorSymbol){yyleng=lexer.yyleng;yytext=lexer.yytext;yylineno=lexer.yylineno;yyloc=lexer.yylloc;if(recovering>0){recovering--}}else{symbol=preErrorSymbol;preErrorSymbol=null}break;case 2:len=this.productions_[action[1]][1];yyval.$=vstack[vstack.length-len];yyval._$={first_line:lstack[lstack.length-(len||1)].first_line,last_line:lstack[lstack.length-1].last_line,first_column:lstack[lstack.length-(len||1)].first_column,last_column:lstack[lstack.length-1].last_column};if(ranges){yyval._$.range=[lstack[lstack.length-(len||1)].range[0],lstack[lstack.length-1].range[1]]}r=this.performAction.apply(yyval,[yytext,yyleng,yylineno,sharedState.yy,action[1],vstack,lstack].concat(args));if(typeof r!=="undefined"){return r}if(len){stack=stack.slice(0,-1*len*2);vstack=vstack.slice(0,-1*len);lstack=lstack.slice(0,-1*len)}stack.push(this.productions_[action[1]][0]);vstack.push(yyval.$);lstack.push(yyval._$);newState=table[stack[stack.length-2]][stack[stack.length-1]];stack.push(newState);break;case 3:return true}}return true}};var lexer=function(){var lexer={EOF:1,parseError:function parseError(str,hash){if(this.yy.parser){this.yy.parser.parseError(str,hash)}else{throw new Error(str)}},setInput:function(input,yy){this.yy=yy||this.yy||{};this._input=input;this._more=this._backtrack=this.done=false;this.yylineno=this.yyleng=0;this.yytext=this.matched=this.match="";this.conditionStack=["INITIAL"];this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0};if(this.options.ranges){this.yylloc.range=[0,0]}this.offset=0;return this},input:function(){var ch=this._input[0];this.yytext+=ch;this.yyleng++;this.offset++;this.match+=ch;this.matched+=ch;var lines=ch.match(/(?:\r\n?|\n).*/g);if(lines){this.yylineno++;this.yylloc.last_line++}else{this.yylloc.last_column++}if(this.options.ranges){this.yylloc.range[1]++}this._input=this._input.slice(1);return ch},unput:function(ch){var len=ch.length;var lines=ch.split(/(?:\r\n?|\n)/g);this._input=ch+this._input;this.yytext=this.yytext.substr(0,this.yytext.length-len);this.offset-=len;var oldLines=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1);this.matched=this.matched.substr(0,this.matched.length-1);if(lines.length-1){this.yylineno-=lines.length-1}var r=this.yylloc.range;this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:lines?(lines.length===oldLines.length?this.yylloc.first_column:0)+oldLines[oldLines.length-lines.length].length-lines[0].length:this.yylloc.first_column-len};if(this.options.ranges){this.yylloc.range=[r[0],r[0]+this.yyleng-len]}this.yyleng=this.yytext.length;return this},more:function(){this._more=true;return this},reject:function(){if(this.options.backtrack_lexer){this._backtrack=true}else{return this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})}return this},less:function(n){this.unput(this.match.slice(n))},pastInput:function(){var past=this.matched.substr(0,this.matched.length-this.match.length);return(past.length>20?"...":"")+past.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var next=this.match;if(next.length<20){next+=this._input.substr(0,20-next.length)}return(next.substr(0,20)+(next.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var pre=this.pastInput();var c=new Array(pre.length+1).join("-");return pre+this.upcomingInput()+"\n"+c+"^"},test_match:function(match,indexed_rule){var token,lines,backup;if(this.options.backtrack_lexer){backup={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done};if(this.options.ranges){backup.yylloc.range=this.yylloc.range.slice(0)}}lines=match[0].match(/(?:\r\n?|\n).*/g);if(lines){this.yylineno+=lines.length}this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:lines?lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+match[0].length};this.yytext+=match[0];this.match+=match[0];this.matches=match;this.yyleng=this.yytext.length;if(this.options.ranges){this.yylloc.range=[this.offset,this.offset+=this.yyleng]}this._more=false;this._backtrack=false;this._input=this._input.slice(match[0].length);this.matched+=match[0];token=this.performAction.call(this,this.yy,this,indexed_rule,this.conditionStack[this.conditionStack.length-1]);if(this.done&&this._input){this.done=false}if(token){return token}else if(this._backtrack){for(var k in backup){this[k]=backup[k]}return false}return false},next:function(){if(this.done){return this.EOF}if(!this._input){this.done=true}var token,match,tempMatch,index;if(!this._more){this.yytext="";this.match=""}var rules=this._currentRules();for(var i=0;i<rules.length;i++){tempMatch=this._input.match(this.rules[rules[i]]);if(tempMatch&&(!match||tempMatch[0].length>match[0].length)){match=tempMatch;index=i;if(this.options.backtrack_lexer){token=this.test_match(tempMatch,rules[i]);if(token!==false){return token}else if(this._backtrack){match=false;continue}else{return false}}else if(!this.options.flex){break}}}if(match){token=this.test_match(match,rules[index]);if(token!==false){return token}return false}if(this._input===""){return this.EOF}else{return this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})}},lex:function lex(){var r=this.next();if(r){return r}else{return this.lex()}},begin:function begin(condition){this.conditionStack.push(condition)},popState:function popState(){var n=this.conditionStack.length-1;if(n>0){return this.conditionStack.pop()}else{return this.conditionStack[0]}},_currentRules:function _currentRules(){if(this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules}else{return this.conditions["INITIAL"].rules}},topState:function topState(n){n=this.conditionStack.length-1-Math.abs(n||0);if(n>=0){return this.conditionStack[n]}else{return"INITIAL"}},pushState:function pushState(condition){this.begin(condition)},stateStackSize:function stateStackSize(){return this.conditionStack.length},options:{},performAction:function anonymous(yy,yy_,$avoiding_name_collisions,YY_START){var YYSTATE=YY_START;switch($avoiding_name_collisions){case 0:return 5;break;case 1:break;case 2:return 8;break;case 3:return 16;break;case 4:return 17;break;case 5:return 11;break;case 6:return 10;break;case 7:return 9;break;case 8:return 14;break;case 9:return 15;break;case 10:return 12;break;case 11:return 7;break;case 12:return 7;break;case 13:return 7;break;case 14:return 13;break;case 15:return 13;break;case 16:return 13;break;case 17:return 13;break;case 18:return 13;break;case 19:return 13;break;case 20:return 13;break;case 21:return 13;break;case 22:return 7;break;case 23:return 7;break;case 24:return 13;break;case 25:return 13;break;case 26:return 13;break;case 27:return 7;break;case 28:return 13;break;case 29:return 13;break;case 30:return 13;break;case 31:return 7;break;case 32:return 7;break;case 33:return 13;break;case 34:return 13;break;case 35:return 13;break;case 36:return 7;break;case 37:return 13;break;case 38:return 7;break;case 39:return 7;break;case 40:return 7;break;case 41:return 7;break;case 42:return 7;break;case 43:return 7;break;case 44:return 7;break;case 45:return 7;break;case 46:return 7;break;case 47:return 7;break;case 48:return 7;break;case 49:return 7;break;case 50:return 7;break;case 51:return 13;break;case 52:return 7;break;case 53:return 7;break;case 54:return 7;break;case 55:return 13;break;case 56:return 7;break;case 57:return 7;break;case 58:return 7;break;case 59:return 13;break;case 60:return 7;break;case 61:return 13;break;case 62:return 7;break;case 63:return 7;break;case 64:return 7;break;case 65:return 7;break;case 66:return 7;break;case 67:return 7;break;case 68:return 7;break;case 69:return 7;break;case 70:return 7;break;case 71:return 7;break;case 72:return 7;break;case 73:return 7;break;case 74:return 7;break;case 75:return 7;break;case 76:return 7;break;case 77:return 7;break;case 78:return 7;break;case 79:return 7;break;case 80:return 7;break;case 81:return 7;break;case 82:return 7;break;case 83:return 7;break;case 84:return 7;break;case 85:return 7;break;case 86:return 7;break;case 87:return 7;break;case 88:return 7;break;case 89:return 7;break;case 90:return 7;break;case 91:return 7;break;case 92:return 7;break;case 93:return 7;break;case 94:return 7;break;case 95:return 7;break;case 96:return 7;break;case 97:return 7;break;case 98:return 7;break;case 99:return 7;break;case 100:return 7;break;case 101:return 7;break;case 102:return 7;break;case 103:return 7;break;case 104:return 7;break;case 105:return 7;break;case 106:return 7;break;case 107:return 7;break;case 108:return 7;break;case 109:return 7;break;case 110:return 7;break;case 111:return 7;break;case 112:return 7;break;case 113:return 7;break;case 114:return 7;break;case 115:return 7;break;case 116:return 7;break;case 117:return 7;break;case 118:return 7;break;case 119:return 7;break;case 120:return 7;break;case 121:return 7;break;case 122:return 7;break;case 123:return 7;break;case 124:return 7;break;case 125:return 7;break;case 126:return 7;break;case 127:return 7;break;case 128:return 7;break;case 129:return 7;break;case 130:return 7;break;case 131:return 7;break;case 132:return 7;break;case 133:return 7;break;case 134:return 7;break;case 135:return 7;break;case 136:return 7;break;case 137:return 7;break;case 138:return 7;break;case 139:return 7;break;case 140:return 7;break;case 141:return 7;break;case 142:return 7;break;case 143:return 7;break;case 144:return 7;break;case 145:return 7;break;case 146:return 7;break;case 147:return 7;break;case 148:return 7;break;case 149:return 7;break;case 150:return 7;break;case 151:return 7;break;case 152:return 7;break;case 153:return 7;break;case 154:return 7;break;case 155:return 7;break;case 156:return 7;break;case 157:return 7;break;case 158:return 7;break;case 159:return 7;break;case 160:return 7;break;case 161:return 7;break;case 162:return 7;break;case 163:return 7;break;case 164:return 7;break;case 165:return 7;break;case 166:return 7;break;case 167:return 7;break;case 168:return 7;break;case 169:return 7;break;case 170:return 7;break;case 171:return 7;break;case 172:return 7;break;case 173:return 7;break;case 174:return 7;break;case 175:return 7;break;case 176:return 7;break;case 177:return 7;break;case 178:return 7;break;case 179:return 7;break;case 180:return 7;break;case 181:return 7;break;case 182:return 7;break;case 183:return 7;break;case 184:return 7;break;case 185:return 7;break;case 186:return 7;break;case 187:return 7;break;case 188:return 7;break;case 189:return 7;break;case 190:return 7;break;case 191:return 7;break;case 192:return 7;break;case 193:return 7;break;case 194:return 7;break;case 195:return 7;break;case 196:return 7;break;case 197:return 7;break;case 198:return 7;break;case 199:return 7;break;case 200:return 7;break;case 201:return 7;break;case 202:return 7;break;case 203:return 7;break;case 204:return 7;break;case 205:return 7;break;case 206:return 7;break;case 207:return 7;break;case 208:return 7;break;case 209:return 7;break;case 210:return 7;break;case 211:return 7;break;case 212:return 7;break;case 213:return 7;break;case 214:return 7;break;case 215:return 7;break;case 216:return 7;break;case 217:return 7;break;case 218:return 7;break;case 219:return 7;break;case 220:return 7;break;case 221:return 7;break;case 222:return 7;break;case 223:return 7;break;case 224:return 7;break;case 225:return 7;break;case 226:return 7;break;case 227:return 7;break;case 228:return 7;break;case 229:return 7;break;case 230:return 7;break;case 231:return 7;break;case 232:return 7;break;case 233:return 7;break;case 234:return 7;break;case 235:return 7;break;case 236:return 7;break;case 237:return 7;break;case 238:return 7;break;case 239:return 7;break;case 240:return 7;break;case 241:return 7;break;case 242:return 7;break;case 243:return 7;break;case 244:return 7;break;case 245:return 7;break;case 246:return 7;break;case 247:return 7;break;case 248:return 7;break;case 249:return 7;break;case 250:return 7;break;case 251:return 7;break;case 252:return 7;break;case 253:return 7;break;case 254:return 7;break;case 255:return 7;break;case 256:return 7;break;case 257:return 7;break;case 258:return 7;break;case 259:return 7;break;case 260:return 7;break;case 261:return 7;break;case 262:return 7;break;case 263:return 7;break;case 264:return 7;break;case 265:return 7;break;case 266:return 7;break;case 267:return 7;break;case 268:return 7;break;case 269:return 7;break;case 270:return 7;break;case 271:return 7;break;case 272:return 7;break;case 273:return 7;break;case 274:return 7;break;case 275:return 7;break;case 276:return 7;break;case 277:return 7;break;case 278:return 7;break;case 279:return 7;break;case 280:return 7;break;case 281:return 7;break;case 282:return 7;break;case 283:return 7;break;case 284:return 7;break;case 285:return 7;break;case 286:return 7;break;case 287:return 7;break;case 288:return 7;break;case 289:return 7;break;case 290:return 7;break;case 291:return 7;break;case 292:return 7;break;case 293:return 7;break;case 294:return 7;break;case 295:return 7;break;case 296:return 7;break;case 297:return 7;break;case 298:return 7;break;case 299:return 7;break;case 300:return 7;break;case 301:return 7;break;case 302:return 7;break;case 303:return 7;break;case 304:return 7;break;case 305:return 7;break;case 306:return 7;break;case 307:return 7;break;case 308:return 7;break;case 309:return 7;break;case 310:return 7;break;case 311:return 7;break;case 312:return 7;break;case 313:return 7;break;case 314:return 7;break;case 315:return 7;break;case 316:return 7;break;case 317:return 7;break;case 318:return 7;break;case 319:return 7;break;case 320:return 7;break;case 321:return 7;break;case 322:return 7;break;case 323:return 7;break;case 324:return 7;break;case 325:return 7;break;case 326:return 7;break;case 327:return 7;break;case 328:return 7;break;case 329:return 7;break;case 330:return 7;break;case 331:return 7;break;case 332:return 7;break;case 333:return 7;break;case 334:return 7;break;case 335:return 7;break;case 336:return 7;break;case 337:return 7;break;case 338:return 7;break}},rules:[/^(?:$)/,/^(?:\s+)/,/^(?:\+)/,/^(?:\()/,/^(?:\))/,/^(?::)/,/^(?:DocumentRef-([0-9A-Za-z-+.]+))/,/^(?:LicenseRef-([0-9A-Za-z-+.]+))/,/^(?:AND)/,/^(?:OR)/,/^(?:WITH)/,/^(?:MPL-2\.0-no-copyleft-exception)/,/^(?:CNRI-Python-GPL-Compatible)/,/^(?:BSD-3-Clause-Attribution)/,/^(?:WxWindows-exception-3\.1)/,/^(?:Classpath-exception-2\.0)/,/^(?:gnu-javamail-exception)/,/^(?:freertos-exception-2\.0)/,/^(?:i2p-gpl-java-exception)/,/^(?:Autoconf-exception-2\.0)/,/^(?:Nokia-Qt-exception-1\.1)/,/^(?:Autoconf-exception-3\.0)/,/^(?:zlib-acknowledgement)/,/^(?:BSD-2-Clause-FreeBSD)/,/^(?:u-boot-exception-2\.0)/,/^(?:Bison-exception-2\.2)/,/^(?:CLISP-exception-2\.0)/,/^(?:BSD-2-Clause-NetBSD)/,/^(?:FLTK-exception-2\.0)/,/^(?:eCos-exception-2\.0)/,/^(?:Font-exception-2\.0)/,/^(?:BSD-3-Clause-Clear)/,/^(?:BSD-3-Clause-LBNL)/,/^(?:GCC-exception-3\.1)/,/^(?:Qwt-exception-1\.0)/,/^(?:GCC-exception-2\.0)/,/^(?:Artistic-1\.0-Perl)/,/^(?:Libtool-exception)/,/^(?:Artistic-1\.0-cl8)/,/^(?:CC-BY-NC-SA-4\.0)/,/^(?:CC-BY-NC-SA-1\.0)/,/^(?:CC-BY-NC-ND-4\.0)/,/^(?:CC-BY-NC-SA-3\.0)/,/^(?:CC-BY-NC-ND-3\.0)/,/^(?:CC-BY-NC-SA-2\.5)/,/^(?:CC-BY-NC-ND-2\.0)/,/^(?:CC-BY-NC-ND-1\.0)/,/^(?:CC-BY-NC-SA-2\.0)/,/^(?:MIT-advertising)/,/^(?:BSD-4-Clause-UC)/,/^(?:CC-BY-NC-ND-2\.5)/,/^(?:FLTK-exception)/,/^(?:SugarCRM-1\.1\.3)/,/^(?:CrystalStacker)/,/^(?:BSD-Protection)/,/^(?:LZMA-exception)/,/^(?:BitTorrent-1\.1)/,/^(?:BitTorrent-1\.0)/,/^(?:Frameworx-1\.0)/,/^(?:mif-exception)/,/^(?:Interbase-1\.0)/,/^(?:389-exception)/,/^(?:HaskellReport)/,/^(?:CC-BY-NC-3\.0)/,/^(?:CC-BY-ND-4\.0)/,/^(?:CC-BY-NC-1\.0)/,/^(?:CC-BY-NC-2\.0)/,/^(?:CC-BY-NC-2\.5)/,/^(?:CC-BY-SA-4\.0)/,/^(?:CC-BY-NC-4\.0)/,/^(?:W3C-19980720)/,/^(?:BSD-4-Clause)/,/^(?:Artistic-1\.0)/,/^(?:BSD-3-Clause)/,/^(?:CC-BY-ND-1\.0)/,/^(?:BSD-2-Clause)/,/^(?:CC-BY-ND-2\.0)/,/^(?:CC-BY-ND-2\.5)/,/^(?:CC-BY-ND-3\.0)/,/^(?:Artistic-2\.0)/,/^(?:CC-BY-SA-1\.0)/,/^(?:CC-BY-SA-2\.0)/,/^(?:CC-BY-SA-2\.5)/,/^(?:CC-BY-SA-3\.0)/,/^(?:XFree86-1\.1)/,/^(?:OLDAP-2\.0\.1)/,/^(?:bzip2-1\.0\.6)/,/^(?:OLDAP-2\.2\.1)/,/^(?:ImageMagick)/,/^(?:Unicode-TOU)/,/^(?:Adobe-Glyph)/,/^(?:CUA-OPL-1\.0)/,/^(?:CNRI-Jython)/,/^(?:CNRI-Python)/,/^(?:bzip2-1\.0\.5)/,/^(?:OLDAP-2\.2\.2)/,/^(?:PostgreSQL)/,/^(?:Apache-1\.1)/,/^(?:CECILL-1\.0)/,/^(?:Apache-2\.0)/,/^(?:Zimbra-1\.4)/,/^(?:CECILL-1\.1)/,/^(?:Zimbra-1\.3)/,/^(?:Adobe-2006)/,/^(?:JasPer-2\.0)/,/^(?:CECILL-2\.0)/,/^(?:TORQUE-1\.1)/,/^(?:CECILL-2\.1)/,/^(?:Watcom-1\.0)/,/^(?:Intel-ACPI)/,/^(?:ClArtistic)/,/^(?:Spencer-99)/,/^(?:Condor-1\.1)/,/^(?:Spencer-94)/,/^(?:gSOAP-1\.3b)/,/^(?:EUDatagrid)/,/^(?:Spencer-86)/,/^(?:Python-2\.0)/,/^(?:RHeCos-1\.1)/,/^(?:CATOSL-1\.1)/,/^(?:Apache-1\.0)/,/^(?:FreeImage)/,/^(?:SGI-B-1\.1)/,/^(?:SGI-B-1\.0)/,/^(?:SimPL-2\.0)/,/^(?:Sleepycat)/,/^(?:Crossword)/,/^(?:ErlPL-1\.1)/,/^(?:CPOL-1\.02)/,/^(?:OLDAP-2\.8)/,/^(?:OLDAP-2\.7)/,/^(?:OLDAP-2\.6)/,/^(?:CC-BY-1\.0)/,/^(?:OLDAP-2\.5)/,/^(?:OLDAP-2\.4)/,/^(?:OLDAP-2\.3)/,/^(?:SISSL-1\.2)/,/^(?:Unlicense)/,/^(?:SGI-B-2\.0)/,/^(?:OLDAP-2\.2)/,/^(?:OLDAP-2\.1)/,/^(?:CC-BY-2\.5)/,/^(?:D-FSL-1\.0)/,/^(?:LPPL-1\.3a)/,/^(?:LPPL-1\.3c)/,/^(?:OLDAP-2\.0)/,/^(?:CC-BY-3\.0)/,/^(?:Leptonica)/,/^(?:OLDAP-1\.4)/,/^(?:OLDAP-1\.3)/,/^(?:OLDAP-1\.2)/,/^(?:OLDAP-1\.1)/,/^(?:MakeIndex)/,/^(?:CC-BY-4\.0)/,/^(?:NPOSL-3\.0)/,/^(?:CC-BY-2\.0)/,/^(?:PHP-3\.01)/,/^(?:ANTLR-PD)/,/^(?:APSL-1\.0)/,/^(?:MIT-enna)/,/^(?:IBM-pibs)/,/^(?:APSL-1\.1)/,/^(?:APSL-1\.2)/,/^(?:Beerware)/,/^(?:EUPL-1\.0)/,/^(?:EUPL-1\.1)/,/^(?:diffmark)/,/^(?:CDDL-1\.0)/,/^(?:Zend-2\.0)/,/^(?:CDDL-1\.1)/,/^(?:CPAL-1\.0)/,/^(?:APSL-2\.0)/,/^(?:LPPL-1\.0)/,/^(?:AGPL-1\.0)/,/^(?:Giftware)/,/^(?:Abstyles)/,/^(?:LPPL-1\.1)/,/^(?:LPPL-1\.2)/,/^(?:Sendmail)/,/^(?:CECILL-B)/,/^(?:AGPL-3\.0)/,/^(?:GFDL-1\.1)/,/^(?:GFDL-1\.2)/,/^(?:GFDL-1\.3)/,/^(?:RPSL-1\.0)/,/^(?:LPL-1\.02)/,/^(?:CECILL-C)/,/^(?:Afmparse)/,/^(?:LGPL-2\.1)/,/^(?:PDDL-1\.0)/,/^(?:ODbL-1\.0)/,/^(?:OCLC-2\.0)/,/^(?:LGPL-3\.0)/,/^(?:Newsletr)/,/^(?:Motosoto)/,/^(?:NBPL-1\.0)/,/^(?:NASA-1\.3)/,/^(?:LGPL-2\.0)/,/^(?:FSFULLR)/,/^(?:MPL-2\.0)/,/^(?:Multics)/,/^(?:AFL-1\.1)/,/^(?:MPL-1\.1)/,/^(?:AFL-1\.2)/,/^(?:MPL-1\.0)/,/^(?:AFL-2\.0)/,/^(?:AFL-2\.1)/,/^(?:AFL-3\.0)/,/^(?:NPL-1\.0)/,/^(?:NPL-1\.1)/,/^(?:APL-1\.0)/,/^(?:Aladdin)/,/^(?:AMDPLPA)/,/^(?:BSL-1\.0)/,/^(?:Borceux)/,/^(?:Caldera)/,/^(?:MIT-CMU)/,/^(?:CPL-1\.0)/,/^(?:ZPL-2\.1)/,/^(?:ZPL-2\.0)/,/^(?:ZPL-1\.1)/,/^(?:CC0-1\.0)/,/^(?:YPL-1\.1)/,/^(?:LPL-1\.0)/,/^(?:libtiff)/,/^(?:YPL-1\.0)/,/^(?:Dotseqn)/,/^(?:Latex2e)/,/^(?:VSL-1\.0)/,/^(?:VOSTROM)/,/^(?:UPL-1\.0)/,/^(?:dvipdfm)/,/^(?:EPL-1\.0)/,/^(?:ECL-1\.0)/,/^(?:ECL-2\.0)/,/^(?:SPL-1\.0)/,/^(?:IPL-1\.0)/,/^(?:EFL-1\.0)/,/^(?:EFL-2\.0)/,/^(?:OPL-1\.0)/,/^(?:OSL-1\.0)/,/^(?:OSL-1\.1)/,/^(?:OSL-2\.0)/,/^(?:OSL-2\.1)/,/^(?:OSL-3\.0)/,/^(?:OpenSSL)/,/^(?:PHP-3\.0)/,/^(?:gnuplot)/,/^(?:Entessa)/,/^(?:GPL-3\.0)/,/^(?:Eurosym)/,/^(?:psutils)/,/^(?:GPL-2\.0)/,/^(?:QPL-1\.0)/,/^(?:MIT-feh)/,/^(?:OFL-1\.1)/,/^(?:GPL-1\.0)/,/^(?:RPL-1\.1)/,/^(?:RPL-1\.5)/,/^(?:OFL-1\.0)/,/^(?:Saxpath)/,/^(?:Bahyph)/,/^(?:RSA-MD)/,/^(?:Naumen)/,/^(?:NetCDF)/,/^(?:mpich2)/,/^(?:Glulxe)/,/^(?:APAFML)/,/^(?:psfrag)/,/^(?:Plexus)/,/^(?:SAX-PD)/,/^(?:MITNFA)/,/^(?:eGenix)/,/^(?:iMatix)/,/^(?:Imlib2)/,/^(?:Libpng)/,/^(?:xinetd)/,/^(?:LGPLLR)/,/^(?:Wsuipa)/,/^(?:SMLNJ)/,/^(?:RSCPL)/,/^(?:SISSL)/,/^(?:Rdisc)/,/^(?:Noweb)/,/^(?:Qhull)/,/^(?:Nunit)/,/^(?:GL2PS)/,/^(?:TMate)/,/^(?:MirOS)/,/^(?:MS-RL)/,/^(?:Intel)/,/^(?:MS-PL)/,/^(?:OGTSL)/,/^(?:WTFPL)/,/^(?:Nokia)/,/^(?:XSkat)/,/^(?:Glide)/,/^(?:FSFUL)/,/^(?:AMPAS)/,/^(?:Xerox)/,/^(?:0BSD)/,/^(?:Ruby)/,/^(?:JSON)/,/^(?:MTLL)/,/^(?:Cube)/,/^(?:Zlib)/,/^(?:NCSA)/,/^(?:TOSL)/,/^(?:Xnet)/,/^(?:DSDP)/,/^(?:HPND)/,/^(?:Barr)/,/^(?:SNIA)/,/^(?:ADSL)/,/^(?:NLPL)/,/^(?:Fair)/,/^(?:NOSL)/,/^(?:NGPL)/,/^(?:SCEA)/,/^(?:Zed)/,/^(?:DOC)/,/^(?:ICU)/,/^(?:Vim)/,/^(?:xpp)/,/^(?:OML)/,/^(?:AAL)/,/^(?:AML)/,/^(?:W3C)/,/^(?:ISC)/,/^(?:IPA)/,/^(?:X11)/,/^(?:MIT)/,/^(?:FTL)/,/^(?:IJG)/,/^(?:TCL)/,/^(?:SWL)/,/^(?:NTP)/,/^(?:Mup)/,/^(?:NRL)/],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338],inclusive:true}}};return lexer}();parser.lexer=lexer;function Parser(){this.yy={}}Parser.prototype=parser;parser.Parser=Parser;return new Parser}();Eif(typeof require!=="undefined"&&typeof exports!=="undefined"){exports.parser=spdxparse;exports.Parser=spdxparse.Parser;exports.parse=function(){return spdxparse.parse.apply(spdxparse,arguments)};exports.main=function commonjsMain(args){if(!args[1]){console.log("Usage: "+args[0]+" FILE");process.exit(1)}var source=require("fs").readFileSync(require("path").normalize(args[1]),"utf8");return exports.parser.parse(source)};Iif(typeof module!=="undefined"&&require.main===module){exports.main(process.argv.slice(1))}}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/

Statements: 12.35% (10 / 81)      Branches: 6.06% (4 / 66)      Functions: 0% (0 / 7)      Lines: 12.5% (10 / 80)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/which/
File Statements Branches Functions Lines
which.js 12.35% (10 / 81) 6.06% (4 / 66) 0% (0 / 7) 12.5% (10 / 80)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/which.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/which.js

Statements: 12.35% (10 / 81)      Branches: 6.06% (4 / 66)      Functions: 0% (0 / 7)      Lines: 12.5% (10 / 80)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 1341 1   1       1 1 1   1             1                                                               1                                                                                       1                                                                              
module.exports = which
which.sync = whichSync
 
var isWindows = process.platform === 'win32' ||
    process.env.OSTYPE === 'cygwin' ||
    process.env.OSTYPE === 'msys'
 
var path = require('path')
var COLON = isWindows ? ';' : ':'
var isexe = require('isexe')
 
function getNotFoundError (cmd) {
  var er = new Error('not found: ' + cmd)
  er.code = 'ENOENT'
 
  return er
}
 
function getPathInfo (cmd, opt) {
  var colon = opt.colon || COLON
  var pathEnv = opt.path || process.env.PATH || ''
  var pathExt = ['']
 
  pathEnv = pathEnv.split(colon)
 
  var pathExtExe = ''
  if (isWindows) {
    pathEnv.unshift(process.cwd())
    pathExtExe = (opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM')
    pathExt = pathExtExe.split(colon)
 
 
    // Always test the cmd itself first.  isexe will check to make sure
    // it's found in the pathExt set.
    if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
      pathExt.unshift('')
  }
 
  // If it has a slash, then we don't bother searching the pathenv.
  // just check the file itself, and that's it.
  if (cmd.match(/\//) || isWindows && cmd.match(/\\/))
    pathEnv = ['']
 
  return {
    env: pathEnv,
    ext: pathExt,
    extExe: pathExtExe
  }
}
 
function which (cmd, opt, cb) {
  if (typeof opt === 'function') {
    cb = opt
    opt = {}
  }
 
  var info = getPathInfo(cmd, opt)
  var pathEnv = info.env
  var pathExt = info.ext
  var pathExtExe = info.extExe
  var found = []
 
  ;(function F (i, l) {
    if (i === l) {
      if (opt.all && found.length)
        return cb(null, found)
      else
        return cb(getNotFoundError(cmd))
    }
 
    var pathPart = pathEnv[i]
    if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"')
      pathPart = pathPart.slice(1, -1)
 
    var p = path.join(pathPart, cmd)
    if (!pathPart && (/^\.[\\\/]/).test(cmd)) {
      p = cmd.slice(0, 2) + p
    }
    ;(function E (ii, ll) {
      if (ii === ll) return F(i + 1, l)
      var ext = pathExt[ii]
      isexe(p + ext, { pathExt: pathExtExe }, function (er, is) {
        if (!er && is) {
          if (opt.all)
            found.push(p + ext)
          else
            return cb(null, p + ext)
        }
        return E(ii + 1, ll)
      })
    })(0, pathExt.length)
  })(0, pathEnv.length)
}
 
function whichSync (cmd, opt) {
  opt = opt || {}
 
  var info = getPathInfo(cmd, opt)
  var pathEnv = info.env
  var pathExt = info.ext
  var pathExtExe = info.extExe
  var found = []
 
  for (var i = 0, l = pathEnv.length; i < l; i ++) {
    var pathPart = pathEnv[i]
    if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"')
      pathPart = pathPart.slice(1, -1)
 
    var p = path.join(pathPart, cmd)
    if (!pathPart && /^\.[\\\/]/.test(cmd)) {
      p = cmd.slice(0, 2) + p
    }
    for (var j = 0, ll = pathExt.length; j < ll; j ++) {
      var cur = p + pathExt[j]
      var is
      try {
        is = isexe.sync(cur, { pathExt: pathExtExe })
        if (is) {
          if (opt.all)
            found.push(cur)
          else
            return cur
        }
      } catch (ex) {}
    }
  }
 
  if (opt.all && found.length)
    return found
 
  throw getNotFoundError(cmd)
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/

Statements: 28.3% (15 / 53)      Branches: 6.12% (3 / 49)      Functions: 0% (0 / 10)      Lines: 28.3% (15 / 53)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/
File Statements Branches Functions Lines
index.js 25.81% (8 / 31) 10% (3 / 30) 0% (0 / 5) 25.81% (8 / 31)
mode.js 31.82% (7 / 22) 0% (0 / 19) 0% (0 / 5) 31.82% (7 / 22)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/index.js

Statements: 25.81% (8 / 31)      Branches: 10% (3 / 30)      Functions: 0% (0 / 5)      Lines: 25.81% (8 / 31)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 591 1 1     1     1 1   1                                                                   1                          
var fs = require('fs')
var core
Iif (process.platform === 'win32' || global.TESTING_WINDOWS) {
  core = require('./windows.js')
} else {
  core = require('./mode.js')
}
 
module.exports = isexe
isexe.sync = sync
 
function isexe (path, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }
 
  if (!cb) {
    if (typeof Promise !== 'function') {
      throw new TypeError('callback not provided')
    }
 
    return new Promise(function (resolve, reject) {
      isexe(path, options || {}, function (er, is) {
        if (er) {
          reject(er)
        } else {
          resolve(is)
        }
      })
    })
  }
 
  core(path, options || {}, function (er, is) {
    // ignore EACCES because that just means we aren't allowed to run it
    if (er) {
      if (er.code === 'EACCES' || options && options.ignoreErrors) {
        er = null
        is = false
      }
    }
    cb(er, is)
  })
}
 
function sync (path, options) {
  // my kingdom for a filtered catch
  try {
    return core.sync(path, options || {})
  } catch (er) {
    if (options && options.ignoreErrors || er.code === 'EACCES') {
      return false
    } else {
      throw er
    }
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/mode.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/which/node_modules/isexe/mode.js

Statements: 31.82% (7 / 22)      Branches: 0% (0 / 19)      Functions: 0% (0 / 5)      Lines: 31.82% (7 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 431 1   1   1           1       1       1                                              
module.exports = isexe
isexe.sync = sync
 
var fs = require('fs')
 
function isexe (path, options, cb) {
  fs.stat(path, function (er, stat) {
    cb(er, er ? false : checkStat(stat, options))
  })
}
 
function sync (path, options) {
  return checkStat(fs.statSync(path), options)
}
 
function checkStat (stat, options) {
  return stat.isFile() && checkMode(stat, options)
}
 
function checkMode (stat, options) {
  var mod = stat.mode
  var uid = stat.uid
  var gid = stat.gid
 
  var myUid = options.uid !== undefined ?
    options.uid : process.getuid && process.getuid()
  var myGid = options.gid !== undefined ?
    options.gid : process.getgid && process.getgid()
 
  var u = parseInt('100', 8)
  var g = parseInt('010', 8)
  var o = parseInt('001', 8)
  var ug = u | g
 
  var ret = (mod & o) ||
    (mod & g) && gid === myGid ||
    (mod & u) && uid === myUid ||
    (mod & ug) && myUid === 0
 
  return ret
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/wrappy/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/wrappy/

Statements: 36.84% (7 / 19)      Branches: 40% (4 / 10)      Functions: 25% (1 / 4)      Lines: 38.89% (7 / 18)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/wrappy/
File Statements Branches Functions Lines
wrappy.js 36.84% (7 / 19) 40% (4 / 10) 25% (1 / 4) 38.89% (7 / 18)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/wrappy/wrappy.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/wrappy/wrappy.js

Statements: 36.84% (7 / 19)      Branches: 40% (4 / 10)      Functions: 25% (1 / 4)      Lines: 38.89% (7 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35          1 1 6   6     6       6   1                                
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
  Iif (fn && cb) return wrappy(fn)(cb)
 
  Iif (typeof fn !== 'function')
    throw new TypeError('need wrapper function')
 
  Object.keys(fn).forEach(function (k) {
    wrapper[k] = fn[k]
  })
 
  return wrapper
 
  function wrapper() {
    var args = new Array(arguments.length)
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i]
    }
    var ret = fn.apply(this, args)
    var cb = args[args.length-1]
    if (typeof ret === 'function' && ret !== cb) {
      Object.keys(cb).forEach(function (k) {
        ret[k] = cb[k]
      })
    }
    return ret
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/write-file-atomic/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/write-file-atomic/

Statements: 22.03% (13 / 59)      Branches: 2.08% (1 / 48)      Functions: 0% (0 / 9)      Lines: 25% (13 / 52)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/node_modules/write-file-atomic/
File Statements Branches Functions Lines
index.js 22.03% (13 / 59) 2.08% (1 / 48) 0% (0 / 9) 25% (13 / 52)
Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/write-file-atomic/index.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/node_modules/write-file-atomic/index.js

Statements: 22.03% (13 / 59)      Branches: 2.08% (1 / 48)      Functions: 0% (0 / 9)      Lines: 25% (13 / 52)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102  1 1 1   1 1 1 1   1 1               1                   1                                           1                         1                                                                          
'use strict'
module.exports = writeFile
module.exports.sync = writeFileSync
module.exports._getTmpname = getTmpname // for testing
 
var fs = require('graceful-fs')
var chain = require('slide').chain
var MurmurHash3 = require('imurmurhash')
var extend = Object.assign || require('util')._extend
 
var invocations = 0
function getTmpname (filename) {
  return filename + '.' +
    MurmurHash3(__filename)
      .hash(String(process.pid))
      .hash(String(++invocations))
      .result()
}
 
function writeFile (filename, data, options, callback) {
  if (options instanceof Function) {
    callback = options
    options = null
  }
  if (!options) options = {}
  fs.realpath(filename, function (_, realname) {
    _writeFile(realname || filename, data, options, callback)
  })
}
function _writeFile (filename, data, options, callback) {
  var tmpfile = getTmpname(filename)
 
  if (options.mode && options.chown) {
    return thenWriteFile()
  } else {
    // Either mode or chown is not explicitly set
    // Default behavior is to copy it from original file
    return fs.stat(filename, function (err, stats) {
      if (err || !stats) return thenWriteFile()
 
      options = extend({}, options)
      if (!options.mode) {
        options.mode = stats.mode
      }
      if (!options.chown && process.getuid) {
        options.chown = { uid: stats.uid, gid: stats.gid }
      }
      return thenWriteFile()
    })
  }
 
  function thenWriteFile () {
    chain([
      [fs, fs.writeFile, tmpfile, data, options.encoding || 'utf8'],
      options.mode && [fs, fs.chmod, tmpfile, options.mode],
      options.chown && [fs, fs.chown, tmpfile, options.chown.uid, options.chown.gid],
      [fs, fs.rename, tmpfile, filename]
    ], function (err) {
      err ? fs.unlink(tmpfile, function () { callback(err) })
        : callback()
    })
  }
}
 
function writeFileSync (filename, data, options) {
  if (!options) options = {}
  try {
    filename = fs.realpathSync(filename)
  } catch (ex) {
    // it's ok, it'll happen on a not yet existing file
  }
  var tmpfile = getTmpname(filename)
 
  try {
    if (!options.mode || !options.chown) {
      // Either mode or chown is not explicitly set
      // Default behavior is to copy it from original file
      try {
        var stats = fs.statSync(filename)
        options = extend({}, options)
        if (!options.mode) {
          options.mode = stats.mode
        }
        if (!options.chown && process.getuid) {
          options.chown = { uid: stats.uid, gid: stats.gid }
        }
      } catch (ex) {
        // ignore stat errors
      }
    }
 
    fs.writeFileSync(tmpfile, data, options.encoding || 'utf8')
    if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
    if (options.mode) fs.chmodSync(tmpfile, options.mode)
    fs.renameSync(tmpfile, filename)
  } catch (err) {
    try { fs.unlinkSync(tmpfile) } catch (e) {}
    throw err
  }
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/scripts/

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/scripts/

Statements: 16.67% (9 / 54)      Branches: 6.25% (2 / 32)      Functions: 0% (0 / 5)      Lines: 17.31% (9 / 52)      Ignored: none     

All files » node-npmtest-npm/node_modules/npm/scripts/
File Statements Branches Functions Lines
changelog.js 11.76% (6 / 51) 6.25% (2 / 32) 0% (0 / 5) 12.24% (6 / 49)
publish-tag.js 100% (3 / 3) 100% (0 / 0) 100% (0 / 0) 100% (3 / 3)
Code coverage report for node-npmtest-npm/node_modules/npm/scripts/changelog.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/scripts/changelog.js

Statements: 11.76% (6 / 51)      Branches: 6.25% (2 / 32)      Functions: 0% (0 / 5)      Lines: 12.24% (6 / 49)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103                          2 2 2       1                       1                                                                           1                                                                  
'use strict'
/*
Usage:
 
node scripts/changelog.js [comittish]
 
Generates changelog entries in our format as best as its able based on
commits starting at comittish, or if that's not passed, latest.
 
Ordinarily this is run via the gen-changelog shell script, which appends
the result to the changelog.
 
*/
const execSync = require('child_process').execSync
const branch = process.argv[2] || 'origin/latest'
const log = execSync(`git log --reverse --pretty='format:%h %H%d %s (%aN)%n%b%n---%n' ${branch}...`).toString().split(/\n/)
 
main()
 
function shortname (url) {
  let matched = url.match(/https:\/\/github.com\/([^/]+\/[^/]+)\/(?:pull|issues)\/(\d+)/)
  if (!matched) return false
  let repo = matched[1]
  let id = matched[2]
  if (repo !== 'npm/npm') {
    return `${repo}#${id}`
  } else {
    return `#${id}`
  }
}
 
function print_commit (c) {
  console.log(`* [\`${c.shortid}\`](https://github.com/npm/npm/commit/${c.fullid})`)
  if (c.fixes) {
    let label = shortname(c.fixes)
    if (label) {
      console.log(`  [${label}](${c.fixes})`)
    } else {
      console.log(`  [#${c.fixes}](https://github.com/npm/npm/issues/${c.fixes})`)
    }
  } else if (c.prurl) {
    let label = shortname(c.prurl)
    if (label) {
      console.log(`  [${label}](${c.prurl})`)
    } else {
      console.log(`  [#](${c.prurl})`)
    }
  }
  let msg = c.message
    .replace(/^\s+/mg, '')
    .replace(/^[-a-z]+: /, '')
    .replace(/^/mg, '  ')
    .replace(/\n$/, '')
  // backtickify package@version
    .replace(/^(\s*[^@\s]+@\d+[.]\d+[.]\d+)(\s*\S)/g, '$1:$2')
    .replace(/\b([^@\s]+@\d+[.]\d+[.]\d+)\b/g, '`$1`')
  // linkify commitids
    .replace(/\b([a-f0-9]{7,8})\b/g, '[`$1`](https://github.com/npm/npm/commit/$1)')
    .replace(/\b#(\d+)\b/g, '[#$1](https://github.com/npm/npm/issues/$1)')
  console.log(msg)
  if (c.credit) {
    c.credit.forEach(function (credit) {
      console.log(`  ([@${credit}](https://github.com/${credit}))`)
    })
  } else {
    console.log(`  ([@${c.author}](https://github.com/${c.author}))`)
  }
}
 
function main () {
  let commit
  log.forEach(function (line) {
    let m
    /*eslint no-cond-assign:0*/
    if (/^---$/.test(line)) {
      print_commit(commit)
    } else if (m = line.match(/^([a-f0-9]{7,9}) ([a-f0-9]+) (?:[(]([^)]+)[)] )?(.*?) [(](.*?)[)]/)) {
      commit = {
        shortid: m[1],
        fullid: m[2],
        branch: m[3],
        message: m[4],
        author: m[5],
        prurl: null,
        fixes: null,
        credit: null
      }
    } else if (m = line.match(/^PR-URL: (.*)/)) {
      commit.prurl = m[1]
    } else if (m = line.match(/^Credit: @(.*)/)) {
      if (!commit.credit) commit.credit = []
      commit.credit.push(m[1])
    } else if (m = line.match(/^Fixes: #?(.*?)/)) {
      commit.fixes = m[1]
    } else if (m = line.match(/^Reviewed-By: @(.*)/)) {
      commit.reviewed = m[1]
    } else if (/\S/.test(line)) {
      commit.message += `\n${line}`
    }
  })
}
 
 
Code coverage report for node-npmtest-npm/node_modules/npm/scripts/publish-tag.js

npmtest-npm (v0.0.1)

Code coverage report for node-npmtest-npm/node_modules/npm/scripts/publish-tag.js

Statements: 100% (3 / 3)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 51 1 1    
var semver = require('semver')
var version = semver.parse(require('../package.json').version)
console.log('v%s.%s-next', version.major, version.minor)